C函数指针妙用,用c语言写一个简易类

来源:互联网 发布:淘宝一箩筐 编辑:程序博客网 时间:2024/05/21 05:55

其实在C++中的对象也并不是实现起来也并不是多麽的什么神秘,只是编译器帮我们做了许多工作,所以我们总觉得C++要比c语言难一些,C++编译器其实对于类中的非Virtual 函数的的调用规则与对C编译器对函数的调用时一样的,那就是通过call 函数地址的方法。等有时间详细的写出来,今天先写虚函数的实现原理:

#include "stdafx.h"#include<stdio.h>struct Person{   char m_szName[10];   int (*pEat)(char food[]);} ;int EatSteak(char food[]){   printf("%s is so great!!!\n", food);   return 0;};int EatChili(char food[]){   printf("%s is so terrible!!!\n", food);   return 0;};int main(void){   struct Person p ;   p.pEat = EatSteak;   p.pEat("Beefsteak");   p.pEat = EatChili;   p.pEat("Chili ");   return 0;}

输出结果是什么?自己试一下吧!!!是不是与虚函数很像,类的虚函数就是这样一个函数指针,在子类初始化时,将子类的函数地址赋值给这个指针。

0 0