c版的回调函数与c++版的虚函数

C语言的回调函数思想代码:

 

#include <stdio.h>

void *max(void *base, unsigned int nmemb, unsigned int size,
    int (*compar)(const void *, const void *))
{
    int i;
    void* max_data = base;
    char* tmp = base;
    for (i=1; i<nmemb; i++) {
        tmp = tmp + size;
        if (compar(max_data, tmp) < 0) {
            max_data = tmp;
        }
    }
    return max_data;
}

int compar_int(const void* x, const void* y)
{
    return (*(int*)x - *(int*)y);
}

typedef struct _Student {
    char name[16];
    int score;
} Student;

int compar_student(const void* x, const void* y)
{
    return (((Student*)x)->score - ((Student*)y)->score);
}

int main()
{
    int data_int[] = {3, 2, 56, 41, 22, 7};
    unsigned int count_int = sizeof(data_int) / sizeof(int);
    int* max_int = (int*)max(data_int, count_int, sizeof(int), &compar_int);
    printf("max int: %d/n", *max_int);

    Student data_student[] = {
        {"Kate", 92},
        {"Green", 85},
        {"Jet", 77},
        {"Larry",88},
    };
    unsigned int count_student = sizeof(data_student) / sizeof(Student);
    Student* high_score = (Student*)max(data_student,
        count_student, sizeof(Student), &compar_student);
    printf("high score -- name:%s, score:%d/n", high_score->name, high_score->score);
   
    return 0;
}

 

 

 

 

C++版的虚函数,在这里它和C代码的回调函数的功能是一样的。

#include<stdio.h>

typedef struct _student { 
      char name[16]; 
       int score; 
} Student;

class int1{
 public:
  virtual int compare(const void* x,const void* y);
  void* max(void *base, unsigned int nmemb, unsigned int size);
 
};

void* int1:: max(void* base, unsigned int nmemb, unsigned int size)
{
  int i;
   void* max_data = base;
   char* tmp =(char*)base;
   for (i=1; i<nmemb; i++) {
     tmp = tmp + size;
     if (compare(max_data, tmp) < 0) {
      max_data = tmp;
    }
   }
   return max_data;

}

int int1::compare(const void* x, const void* y){
  return (*(int*)x - *(int*)y);
}

class student : public int1{
  public:
   int compare(const void* x, const void* y);

  };
  

int student::compare(const void* x, const void* y)
{
 return (((Student*)x)->score - ((Student*)y)->score);
}


int main()
{
 
    Student data_student[] = {
        {"Kate", 92},
        {"Green", 85},
        {"Jet", 77},
        {"Larry",88},
    };
 student B;
 unsigned count_student= sizeof(data_student)/sizeof(Student);
 Student* high_score=(Student*)B.max(data_student,count_student,sizeof(Student));
 printf("high score --name:%s,score:%d/n",high_score->name,high_score->score);
}

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值