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


一、运行时多态

#include<iostream>
#include<string>
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();
}

在这里插入图片描述
结果如上图所示。

猜你喜欢

转载自blog.csdn.net/taiyuezyh/article/details/124271723