c++利用初始化列表在類內部和類外部定義構造函數的區別


case 1:在類外定義構造函數,所有data member都在初始化列表中進行初始化。

class SupportClass
{
public:
	SupportClass()
	{
		cout << "SupportClass() is called" << endl;
	}
	SupportClass(SupportClass&)
	{
		cout << "SupportClass(SupportClass&) is called" << endl;
	}
	~SupportClass()
	{
		cout << "~SupportClass() is called" << endl;
	}
	SupportClass& operator=(SupportClass&)
	{
		cout << "SupportClass()& operator=(SupportClass&) is called" << endl;
		return *this;
	}
};

class TestInitialize
{
public:
	TestInitialize(SupportClass arg);
private:
	SupportClass data;
};

TestInitialize::TestInitialize(SupportClass arg) :data(arg){}

int main()
{
	SupportClass sc;
	cout << endl;
	TestInitialize ti(sc);
	return 0;
}

  

結果:

 

 第一次默認構造:來自main函數中定義的變量sc;

第二次拷貝構造:來自形參拷貝實參;

第三次拷貝構造:來自data member 拷貝形參。

結論:與類內定義一樣。

case 2:在類外定義構造函數,初始化列表為空,data member 在函數體中定義。

TestInitialize::TestInitialize(SupportClass arg) { data = arg; }

  結果;

 

 

 第一次默認構造:來自main函數中定義的變量sc;

第二次拷貝構造:來自形參拷貝實參;

第三次默認構造:來自data member 的默認初始化。

接着的 operator=:data 復制 形參。

結論:與類內定義一樣。

case 3:類有多個 data 成員,全用初始化列表初始化,函數體為空

添加一個class:AnotherClass

class AnotherSupportClass
{
public:
	AnotherSupportClass()
	{
		cout << "AnotherSupportClass() is called" << endl;
	}
	AnotherSupportClass(AnotherSupportClass&)
	{
		cout << "AnotherSupportClass(AnotherSupportClass&) is called" << endl;
	}
	~AnotherSupportClass()
	{
		cout << "~AnotherSupportClass() is called" << endl;
	}
	AnotherSupportClass& operator=(AnotherSupportClass&)
	{
		cout << "AnotherSupportClass()& operator=(AnotherSupportClass&) is called" << endl;
		return *this;
	}
};
TestInitialize::TestInitialize(SupportClass arg1, AnotherSupportClass arg2)
:data(arg1), anotherData(arg2){}

 結果:

 

意外發現: 

我的構造函數的參數列表是:先SupportClass,然后再AnotherSupportClass。

結果在由實參拷貝到形參時時:先AnotherSupportClass,再SupportClass。

又做了一個實驗:再添加一個成員

class TestInitialize
{
public:
	TestInitialize(SupportClass arg1, AnotherSupportClass arg2,OtherSupportClass arg3);
private:
	SupportClass data;
	AnotherSupportClass anotherData;
	OtherSupportClass otherData;
};

TestInitialize::TestInitialize(SupportClass arg1, AnotherSupportClass arg2, OtherSupportClass arg3)
:data(arg1), anotherData(arg2),otherData(arg3){};

 

 依舊是逆序拷貝構造的,重點是我不信邪,循環了100次,都是這個結果。

結論:函數參數列表的拷貝是隨機的,並不是按照參數出現的先后順序。

case 4:函數只能被定義一次,要么在函數內,要么在函數外。使用初始化列表初始化時必須定義函數!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM