zoukankan      html  css  js  c++  java
  • 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("
    ");
    13 
    15    if(pValidator->validate(pValidator,num) == true)
    16    {
    17         printf("The %d in range of 1 to 10
    ",num);
    18    }
    19    else
    20    {
    21         printf("The %d not in range of 1 to 10
    ",num);
    22    }
    23     printf("
    ");
    24 
    25    OddEvenValidator oddEvenValidator = newOddEvenValidator(true);// 初始化OddEvenValidator
    26    pValidator = &oddEvenValidator.isa;
    27 
    28     printf("Pease input an integer: ");
    29    scanf("%d",&num);
    30    printf("
    ");
    31 
    32    if(pValidator->validate(pValidator,num) == true)
    33    {
    34         printf("The %d is an even.
    ",num);
    35    }
    36    else
    37    {
    38         printf("The %d is an odd.
    ",num);
    39    }
    40     return 0;
    41 }
  • 相关阅读:
    filter函数和map函数
    生成器面试题
    装饰器激活生成器
    移动平均値
    send()方法的初识
    监听文件的输入
    迭代器抛出异常处理方法
    装饰器-wraps
    多个装饰器装饰一个函数
    WebView 安卓原生java与h5,js交互
  • 原文地址:https://www.cnblogs.com/chenweilin/p/10308506.html
Copyright © 2011-2022 走看看