c++繼承構造函數

#include <iostream>

using namespace std;

struct Base
{
	Base::Base(){}
	void f(double i)
	{
		cout << "Base :" << i << endl;
	}
};

struct Derived : Base
{
	using Base::Base;//通過這個聲明,可以把基類中的所有構造函數悉數繼承到派生類B中

	using Base::f;//派生類要使用基類的成員函數,可以使用using 聲明
	void f(int i)
	{
		cout << "Derived :" << i << endl;
	}
};

struct A
{
	A(int i){}
};

struct B : A
{
	using A::A;//這裏使用了繼承構造函數,編譯器將不再生成默認構造函數
};
//當我們實例化B時,
//B b1;//報錯 : error C2512: “B”: 沒有合適的默認構造函數可用 

int main()
{
	Base base;
	base.f(2.4);
	Derived dev;
	dev.f(2.4);//當不加 using Base::f;時,這裏輸出的是Derived :2,當加上時,輸出的是Base :2.4
	system("pause");
	return 0;
}

注意:一旦使用繼承構造函數,編譯器就不會再爲派生類生成默認構造函數了

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章