/* 用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請按任意鍵繼續. . .*/