转载详情,请参考:
https://blog.csdn.net/qq_15079039/article/details/80917734
这里对其中一篇进行展示:
C语言和设计模式(继承、封装、多态)
#include<stdio.h>
//多态
typedef struct Human {
int age;
void(*say)(void);
}Human;
Human newHuman() {
Human human;
human.age = 1;
return human;
}
typedef struct Student {
Human human;
}Student;
void studentSay(void) {
printf("studentSay\n");
}
Student newStudent() {
Student s;
s.human = newHuman();
s.human.say = studentSay;
return s;
}
typedef struct Teacher {
Human human;
}Teacher;
void teacherSay(void) {
printf("teacherSay\n");
}
Teacher newTeacher() {
Teacher t;
t.human = newHuman();
t.human.say = teacherSay;
return t;
}
void function(Human human) {
human.say();
printf("age is:%d\n",human.age);
}
int main() {
Teacher t = newTeacher();
Student s = newStudent();
t.human.age = 12;
s.human.age = 33;
function(s.human);
function(t.human);
return 1;
}