c版的回调函数与c++版的虚函数
来源:互联网 发布:算法公开课 编辑:程序博客网 时间:2024/06/11 22:07
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);
}
- c版的回调函数与c++版的虚函数
- C 函数指针与回调函数
- C/C++ 不带参数的回调函数 与 带参数的回调函数 函数指针数组 例子
- c的回调函数与java中抽象函数,接口函数,抽象类简单理解
- C/C++之回调函数---函数指针的作用
- C/C++之回调函数---函数指针的作用
- C/C++之回调函数---函数指针的作用
- 重学C++Primer笔记9---回调函数与函数指针的应用
- Fortran与C语言,回调函数的使用比较
- C#中的委托与C语言的回调函数
- c下面的回调函数
- 学习C语言的回调函数
- 一个c回调函数的例子
- 一个c回调函数的例子
- C回调函数的简单实例
- C的回调函数--曾经难为情
- 一个c回调函数的例子
- 一个c回调函数的例子
- AJAX 表格字段数据排序,点击表头每列排序
- 来自MIT人工智能实验室:如何做研究?
- 猫叫问题二
- WCF初体验—“Hello Matrix”
- 分页的存储过程
- c版的回调函数与c++版的虚函数
- 知其所以然技术论坛资源下载
- 《C#与.NET3.0高级程序设计》摘要-----第三章 C#语言基础
- Asp.net 自定义控件,最后产生的页面就依靠Render了
- 2010.2月总结
- 《悟透javascript》学习笔记
- 6.HQL入门
- Vista、Win7 网络共享访问慢的解决方案
- memcopy引起的glibc detecte错误