浏览 4940 次
锁定老帖子 主题:c语言实现面向对象编程
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2020-12-04
复制代码 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 } 复制代码 看到这里就说明你是在学习的不妨看看下边这些资料看看适不适合自己 C语言实现面向对象编程 http://www.makeru.com.cn/live/1392_1051.html?s=45051 结构体普及与应用 http://www.makeru.com.cn/live/5413_1909.html?s=45051 C语言玩转链表 http://www.makeru.com.cn/live/1392_338.html?s=45051 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |