C语言实现面向对象编程

来源:互联网 发布:各项异性采样优化 编辑:程序博客网 时间:2024/05/19 07:09
/*    用C语言实现面向对象编程。huyelei@yeah.net 2013.01.09本程序中建立了结构体Student, 成员age和number模拟类的数据成员,成员setAge,getAge和showNumber模拟类的函数成员(类的方法)本程序测试方法:在VC中建立空白的Win32 Console型工程,为工程添加新源文件main.c(若main.cpp,则使用C++编译器)    将本程序拷贝到main.c中即可测试。*/#include <stdio.h>typedef void (*SetAge)(int age, void* pThis); /// 声明函数指针类型typedef int (*GetAge)(void* pThis);typedef int (*ShowNumber)(void* pThis);struct Student{int age;SetAge setAge;GetAge getAge;int number;ShowNumber showNumber;};void Student_SetAge(int _age, void* _pThis) // 对应 Student::SetAge{struct Student* pThis = (struct Student*)_pThis;pThis->age = _age; }int Student_GetAge(void* _pThis){struct Student* pThis = (struct Student*)_pThis;return pThis->age;}int Student_ShowNumber(void* _pThis){struct Student* pThis = (struct Student*)_pThis;printf("student number: %d \n", pThis->number);}void constructor(struct Student* pThis){pThis->age = 0;pThis->setAge = Student_SetAge;pThis->getAge = Student_GetAge;pThis->number = 9527; // 周星星工号pThis->showNumber = Student_ShowNumber;}void main(void){// 以下两句 对应C++的 Student a();struct Student a; constructor(&a);// C++正调用方式为a.setAge(10),由C++编译器首先转成a.setAge(10, &a)的形式,然后编译成机器指令// C语言编译器没有该功能,所有手动添加参数"&a"a.setAge(10, &a);printf("age %d \n", a.getAge(&a));a.showNumber(&a);}/*程序输出结果:age 10student number: 9527请按任意键继续. . .*/