C++多态实现

C++多态实现,第1张

C++多态实现
#include 
#include 
using namespace std;



using EatPtr = function;
using PlayPtr = function;
struct VirtualTable {
	EatPtr m_eat;
	PlayPtr m_play;
};

struct base {
	VirtualTable m_table;
};

struct DeriveA {
	base m_base;
};

struct DeriveB {
	base m_base;
};

void baseEat() {
	cout << "base eat" << endl;
}

void basePlay() {
	cout << "base play" << endl;
}

void DeriveAEat() {
	cout << "derive a eat" << endl;
}
void DeriveAPlay() {
	cout << "derive a play" << endl;
}

void DeriveBEat() {
	cout << "derive b eat" << endl;
}
void DeriveBPlay() {
	cout << "derive b play" << endl;
}



int main() {
	DeriveA a;
	DeriveB b;
	a.m_base.m_table.m_eat = DeriveAEat;
	a.m_base.m_table.m_play = DeriveAPlay;
	
	b.m_base.m_table.m_eat = DeriveBEat;
	b.m_base.m_table.m_play = DeriveBPlay;
	
	base* basea = (base*)&a;
	basea->m_table.m_eat();
	basea->m_table.m_play();
	
	base* baseb = (base*)&b;
	baseb->m_table.m_eat();
	baseb->m_table.m_play();
	return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5718464.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存