1

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

 2 years ago
source link: https://www.lpime.cn/article/121
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

重写

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

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

  • 不在同一个作用域(分别在基类和派生类)
  • 函数名相同、参数相同、返回值相同(协变除外)
  • 基类函数必须含有virtual关键字
  • 访问修饰符可以不同

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;
}

本文由 Ryan 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: 2021/09/30 16:03


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK