這篇部落格參考了:http://soft-app.iteye.com/blog/922040
上面的部落格講的比較詳細,解釋了複制構造函數和指派函數的差別,在這裡通過相關代碼解釋複制構造函數和指派函數的差別,還有需要注意初始化時的隐式類型轉換。
#include <iostream>
using namespace std;
class test
{
public:
test() // 1. 預設構造函數。
{
cout << "default consturctor" << endl;
}
test(int i) // 2. 帶參數的構造函數。
{
a = i;
cout <<"test(int i)" << endl;
}
test(const test & other) // 3. 複制構造函數。
{
a = other.a;
cout << "copy constructor" << endl;
}
test& operator=(const test& other) // 4. 指派函數。
{
a = other.a;
cout << "assignment" << endl;
return *this;
}
private:
int a;
};
int main(int argc, char* argv[])
{
// 1.測試一
test t1; // 調用t1的預設構造函數;
test t2 = t1; // 調用t2的複制構造函數,因為在這裡t2屬于執行個體化時期,是以不是指派函數
t2 = t1; // 調用t2的指派函數,因為這裡t2執行個體化過程已經完成,是以調用的是指派函數。
test t3(t1); // 調用t3的複制構造函數,這裡t3屬于執行個體化時期。
test t4 = t3 = t2; // 調用t3的指派函數,調用t4的複制函數。
// 2.測試二
test a = 20; // 調用帶int參數的構造函數,這裡存在内置資料類型向類類型的隐式轉換。
test b = a; // 調用b的複制構造函數。
return 0;
}