C语言实现C++多态之诸葛亮的锦囊妙计
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stdlib.h>
using namespace std;
//C语言多态
/**********抽象层***********/
typedef void (TIPS)(void); //抽象架构
//定义具体的锦囊
struct tip
{
char from[64]; //谁写的
char to[64]; //写给谁的
//锦囊的内容
TIPS*tp; //相当于抽象类的纯虚函数
};
//打开锦囊的架构函数
void open_tips(struct tip*tip_num)
{
cout << "打开了锦囊" << endl;
cout << "此锦囊是由" << tip_num->from << "写
给" << tip_num->to << "的。" << endl;
cout << "内容是" << endl;
//此处发生多态现象
tip_num->tp();
}
void (*openptr[200])(struct tip*tip_num); //函数指针数组
//提供构造函数
struct tip*create_tip(const char*from,const char*to,TIPS*tip)
{
struct tip*temp = (struct tip*)malloc(sizeof(struct
tip));
if (temp == NULL) {
return NULL;
}
strcpy(temp->from,from);
strcpy(temp->to,to);
//注册回调函数
temp->tp = tip;
return temp;
}
//提供析构
void destroy_tip(struct tip*tp)
{
if (tp != NULL)
{
free(tp);
tp = NULL;
}
return;
}
/**********实现层***********/
void tip1_fun(void)
{
cout << "一到东吴就拜会乔国老" << endl;
}
void tip2_fun(void)
{
cout << "曹操大军压境,劝刘备回荆州" << endl;
}
void tip3_fun(void)
{
cout << "危急时刻向孙尚香求救" << endl;
}
/**********业务层***********/
int main()
{
//创建三个锦囊
struct tip*tp1 = create_tip("孔明","赵云",tip1_fun);
struct tip*tp2 = create_tip("孔明", "赵云", tip2_fun);
struct tip*tp3 = create_tip("孔明", "赵云", tip3_fun);
//架构调用
cout << "刚刚来到东吴,赵云打开第一个锦囊" <<
endl;
open_tips(tp1);
cout << "===================" << endl;
cout << "刘备乐不思蜀,年底赵云打开第二个锦囊"
<< endl;
open_tips(tp2);
cout << "======================" << endl;
cout << "孙权大军追杀,赵云打开第三个锦囊" <<
endl;
open_tips(tp3);
//释放内存
destroy_tip(tp1);
destroy_tip(tp2);
destroy_tip(tp3);
system("pause");
return 0;
}