1、c语言实现多态
1.1、函数指针定义,简单使用
《c语言 函数指针(三种定义方式,回调函数使用)》.
先定义一个函数指针类型(TIPS,返回值参数都是void),在定义一个结构体中包含这个函数指针成员,想使用这个结构体就必须传入一个TIPS类型的函数地址进来,和C++中纯虚函数一样,通过传入的函数地址不同,进行回调实现多态现象
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
抽象层
*/
// 定义一个锦囊函数类型
typedef void(TIPS)(void);
// 定义锦囊
struct tip
{
char form[64]; // 谁写的
char to[64]; // 写给谁
TIPS* tp; // 相当于抽象类的,纯虚函数,想要定义你锦囊就要定义锦囊函数
};
> 定义
void tip1(void)
{
printf("一到东吴就拜会乔国老\n");
}
void tip2(void)
{
printf("如果主公乐不思蜀,就谎称曹贼来袭,赶紧走\n");
}
void tip3(void)
{
printf("孙权追杀,就向孙尚香求救\n");
}
/*
实现层
*/
// 需要一个打开锦囊的架构函数
void open_tips(struct tip* tip_p)
{
printf("打开锦囊\n");
printf("此锦囊是有%s-》写给%s",tip_p->form,tip_p->to);
printf("内容:");
tip_p->tp();
}
struct tip* create_tip(char* form,char* to,TIPS* tp)
{
struct tip* temp = (struct tip*)malloc(sizeof(struct tip));
strcpy(temp->form,form);
strcpy(temp->to,to);
temp->tp = tp;
return temp;
}
void free_tip(struct tip* tip_p)
{
if(tip_p!= NULL)
{
free(tip_p);
tip_p = NULL;
}
}
int main(void)
{
struct tip* p1 = create_tip("诸葛亮","刘备",tip1);
struct tip* p2 = create_tip("诸葛亮","刘备",tip2);
struct tip* p3 = create_tip("诸葛亮","刘备",tip3);
open_tips(p1);
open_tips(p2);
open_tips(p3);
free_tip(p1);
free_tip(p2);
free_tip(p3);
return 0;
}
2、c++实现多态
和c的差别:把结构体换成了类,把类中纯虚函数换成了,函数指针,类中通过通过父类指针指向不同的子类,实现多态现象,结构体中,通过传入的函数地址,通过函数指针进行函数调用,实现多态现象,c++本质也是采用c的回调函数函数实现
#include <iostream>
#include <string>
using namespace std;
class tip
{
public:
virtual void tips()=0;
string form;
string to;
};
class tip1:public tip
{
public:
tip1(string form,string to)
{
this->form = form;
this->to = to;
}
virtual void tips()
{
cout<<"一到东吴就拜会乔国老"<<endl;
}
};
class tip2:public tip
{
public:
tip2(string form,string to)
{
this->form = form;
this->to = to;
}
virtual void tips()
{
cout<<"如果主公乐不思蜀,就谎称曹贼来袭,赶紧走"<<endl;
}
};
class tip3:public tip
{
public:
tip3(string form,string to)
{
this->form = form;
this->to = to;
}
virtual void tips()
{
cout<<"孙权追杀,就向孙尚香求救"<<endl;
}
};
void open_tip(tip* p)
{
cout<<p->form<<"给"<<p->to<<"的锦囊妙计:"<<endl;
p->tips();
}
void free_tip(tip* p)
{
if(p!=NULL)
{
free(p);
p = NULL;
}
}
int main(void)
{
tip* p1 = new tip1("诸葛亮","刘备");
tip* p2 = new tip2("诸葛亮","刘备");
tip* p3 = new tip3("诸葛亮","刘备");
open_tip(p1);
open_tip(p2);
open_tip(p3);
free_tip(p1);
free_tip(p2);
free_tip(p3);
return 0;
}