您的位置:首页 > 编程语言 > C语言/C++

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: