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:函數只能被定義一次,要么在函數內,要么在函數外。使用初始化列表初始化時必須定義函數!
