C语言实现多态
2016-05-06 22:05
537 查看
/* filename:c_duotai.c author:cc time:2016-05-06 */ #include<stdio.h> #include<string.h> struct Human //基类 { char Memoryalign[20]; //对齐内存, 很重要 void (*input)(struct Human *thiz); //虚函数 float (*score)(struct Human *thiz); //虚函数 void (*show)(struct Human *thiz); //虚函数 }; struct Student //派生类 { char m_name[12]; int m_age; float m_score; //具体方法 void (*input)(struct Student *thiz, char *name, int age, float score); float (*score)(struct Student *thiz); void (*show)(struct Student *thiz); void (*change_score)(struct Student *thiz, float new_score); //派生类单独具有的函数 }; ////////////////////////////////////////////////////////////////////////////////// void input_infor(struct Student *thiz, char *name, int age, float score) { memmove((*thiz).m_name,name, strlen(name)); (*thiz).m_age = age; (*thiz).m_score = score; } float get_score(struct Student *thiz) { return (*thiz).m_score; } void show_infor(struct Student *thiz) { printf("name :%s\n", (*thiz).m_name); printf("age:%d\n", (*thiz).m_age); printf("score:%f\n", (*thiz).m_score); } void change_infor(struct Student *thiz, float new_score) { (*thiz).m_score = new_score; } void Init_Student(struct Student *thiz, char *name, int age, float score) //子类构造函数 { memset((*thiz).m_name, '\0', 12); memmove((*thiz).m_name,name, strlen(name)); (*thiz).m_age = age; (*thiz).m_score = score; (*thiz).input = input_infor; (*thiz).score = get_score; (*thiz).show = show_infor; (*thiz).change_score = change_infor; } //////////////////////////////////////////////////////////////////////////////// int main() { struct Student stu; //派生类对象 struct Human *human = (struct Human *)&stu; //基类指针指向派生类对象 Init_Student(&stu, "caocao", 23, 98); //派生类对象调用构造函数 printf("%f\n", human->score(human)); //基类指针调用派生类中的函数。 return 0; }
相关文章推荐
- 国外程序员整理的 C++ 资源大全
- Problem I: C语言实验——打印数字图形
- 动态创建对象
- More Effective C++----(24)理解虚拟函数、多继承、虚继承和RTTI所需的代价
- 斐波那契数列的非递归c语言实现以及斐波那契数列的应用
- C++ Primer 学习笔记_44_STL实践与分析(18)--再谈迭代器【下】
- C++ Primer 学习笔记_43_STL实践与分析(17)--再谈迭代器【中】
- C++ Primer 学习笔记_42_STL实践与分析(16)–再谈迭代器【上】
- c++ STL 工程实践的15条建议
- C++ Primer 学习笔记_41_STL实践与分析(15)--先来看看算法【下一个】
- C++ Primer 学习笔记_40_STL实践与分析(14)--概要、先来看看算法【上】
- C++ Primer 学习笔记_39_STL实践与分析(13)--multimap与multiset
- C++ Primer 学习笔记_38_STL实践与分析(12)--容器的综合应用:文本查询程序
- C++ Primer 学习笔记_37_STL实践与分析(11)--set类型
- C++ Primer 学习笔记_36_STL实践与分析(10)--map类型(下
- C++ Primer 学习笔记_35_STL实践与分析(9)--map种类(在)
- C++ Primer 学习笔记_34_STL实践与分析(8) --引言、pair类型、关联容器
- 优先队列(堆)笔记 c++
- 深入分析C++引用
- static在C和C++里各代表什么含义