c语言实现面向对象编程

1.通用校验器接口(validator.h)

 

 1 #ifndef VALIDATOR_H_INCLUDED
 2 #define VALIDATOR_H_INCLUDED
 3 
 4 #include<stdbool.h>
 5 
 6 typedef struct _Validator{
 7     bool (*const validate)(struct _Validator *pThis, int value);
 8 }Validator;
 9 
10 typedef struct{
11     Validator isa;    //结构体成员
12     const int min;
13     const int max;
14 } RangeValidator;
15 
16  typedef struct{
17     Validator isa;    //结构体成员
18     bool isEven;
19  } OddEvenValidator;
20 
21 bool validateRange(Validator *pThis, int value); // 范围校验器函数
22 bool validateOddEven(Validator *pThis, int value); // 奇偶校验器函数
23 #define newRangeValidator(min, max) {{validateRange}, (min), (max)} // 初始化RangeValidator
24 #define newOddEvenValidator(isEven) {{validateOddEven}, (isEven)} //  初始化OddEvenValidator
25 
26 #endif // VALIDATOR_H_INCLUDED

2.通用校验器接口实现(validator.c)

 

 1 #include "validator.h"
 2 
 3 bool validateRange(Validator *pThis, int value)
 4 {
 5     RangeValidator *pRangeValidator = (RangeValidator *)pThis;
 6     return pRangeValidator -> min <= value && value <= pRangeValidator -> max;
 7 }
 8 
 9 bool validateOddEven(Validator *pThis, int value)
10 {
11     OddEvenValidator *pOddEvenValidator = (OddEvenValidator *)pThis;
12     return (!pOddEvenValidator -> isEven && (value % 2)) || (pOddEvenValidator -> isEven && !(value % 2));
13 }

3.通用校验器使用范例程序

 

 1 #include <stdio.h>
 2 #include "validator.h"
 3 
 4 int main()
 5 {
 6    int  num;
 7    RangeValidator rangeValidator = newRangeValidator(1, 10);// 初始化RangeValidator
 8    Validator *pValidator = &rangeValidator.isa;
10    printf("Pease input an integer: ");
11    scanf("%d",&num);
12    printf("\n");
13 
15    if(pValidator->validate(pValidator,num) == true)
16    {
17         printf("The %d in range of 1 to 10\n",num);
18    }
19    else
20    {
21         printf("The %d not in range of 1 to 10\n",num);
22    }
23     printf("\n");
24 
25    OddEvenValidator oddEvenValidator = newOddEvenValidator(true);// 初始化OddEvenValidator
26    pValidator = &oddEvenValidator.isa;
27 
28     printf("Pease input an integer: ");
29    scanf("%d",&num);
30    printf("\n");
31 
32    if(pValidator->validate(pValidator,num) == true)
33    {
34         printf("The %d is an even.\n",num);
35    }
36    else
37    {
38         printf("The %d is an odd.\n",num);
39    }
40     return 0;
41 }

 

posted @ 2019-01-23 13:44  青山依  阅读(2108)  评论(0编辑  收藏  举报