C++:函数重写与协变返回类型

/ C++ / 没有评论 / 1245浏览

C++函数重写与协变返回类型

1.函数重写(覆盖)满足的条件:

2.协变返回类型

​ 重写的函数与被重写的函数返回值类型相同,或者当返回指针或者引用时(不包括vaue语义),子类中重写的函数返回的指针或者引用是父类中被重写函数所返回指针或引用的子类型(这就是所谓的covariant return type:协同返回类型)

例子:

#include<iostream>

using namespace std;

class Base {
public:
	Base() { cout << "Base Creted" << endl; }
	virtual ~Base() { cout << "Base Destroyed" << endl; }
	virtual Base* func() {
		cout << "Base" << endl;
		return new Base();
	}
	virtual void GetA()
	{

	}
};

class Derived : public Base {
public:
	Derived() { cout << "Derived Created" << endl; }
	~Derived() { cout << "Derived Destroyed" << endl; }
	virtual Derived* func() {
		cout << "Derived" << endl;
		return new Derived();
	}
	
	virtual void GetA()
	{
		cout << "aaa" << endl;
	}
};

int main()
{
	Base *pB = new Derived();
	//发生协变
	Base *p = pB->func();
	
	p->GetA();

	delete pB;
	pB = NULL;
	delete p;
	p = NULL;
	system("pause");
	return 0;
}