C++学习日志38---运行时多态、虚函数与覆写

C++学习日志38---运行时多态、虚函数与覆写,第1张

目录
  • 一、运行时多态


一、运行时多态
#include
#include
using std::cout;
using std::endl;
//任务1:创建A/B/C三个类,B继承A,C继承B,ABC均有toString函数
//任务2:重载print函数,接受B/C类型参数,调用toString()
class A
{
public:
	virtual std::string toString() { return "A"; }
};

class B :public A
{
public:
	std::string  toString() override { return "B"; }
};

class C :public B
{
public:
	std::string toString() override  { return "C"; }
};
void print(A* o)
{
	cout << o->toString() << endl;
}
void print(A& o)
{
	cout << o.toString() << endl;
}
int main()
{
	A a;
	B b;
	C c;
	A* p1 = &a;
	A* p2 = &b;
	A* p3 = &c;
	print(a);
	print(b);
	print(c);

	print(a);
	print(b);
	print(c);

	std::cin.get();
}


结果如上图所示。

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

原文地址: https://outofmemory.cn/langs/713600.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)

保存