1 . 用同一個類的來源物件構造一個目標對象時,會調用拷貝建構函式來構造目標對象,如果沒有定義拷貝建構函式,將調用類的預設拷貝函數來構造目標對象。
2 . 當一個函數的傳回值為一個類的對象時,如果在調用函數中,沒有定義一個對象來接收這個返回對象值,會用返回一個臨時對象儲存返回對象的值。在被調用函數結束時,這個臨時對象被銷毀。而當調用函數中有一個接受對象時,就將返回對象賦值給接收對象,這個返回對象在調用函數結束時調用解構函式。
3. 當類有一個帶有一個參數的建構函式時,可以用這個參數同類型的資料初始化這個對象,預設會調用這個建構函式。
複製代碼 代碼如下: #include "stdafx.h"
#include <iostream>
using namespace std;
class B
{
public:
B():data(0) //預設建構函式
{
cout << "Default constructor is called." << endl;
}
B(int i):data(i) //帶參數的建構函式
{
cout << "Constructor is called." << data << endl;
}
B(B &b) // 複製(拷貝)建構函式
{
data = b.data; cout << "Copy Constructor is called." << data << endl;
}
B& operator = (const B &b) //賦值運算子的重載
{
this->data = b.data;
cout << "The operator \"= \" is called." << data << endl;
return *this;
}
~B() //解構函式
{
cout << "Destructor is called. " << data << endl;
}
private:
int data;
};
//函數,參數是一個B類型對象,傳回值也是一個B類型的對象
B fun(B b)
{
return b;
}
//測試函數
int _tmain(int argc, _TCHAR* argv[])
{
fun(1);
cout << endl;
B t1 = fun(2);
cout << endl;
B t2;
t2 = fun(3);
return 0;
}
複製代碼 代碼如下:輸出結果為:
複製代碼 代碼如下: Constructor is called.1 //用1構造參數b
Copy Constructor is called.1 //用b拷貝構造一個臨時對象,因為此時沒有對象來接受fun的傳回值
Destructor is called. 1 //參數b被析構
Destructor is called. 1 //臨時對象被析構
Constructor is called.2 //用2構造參數b
Copy Constructor is called.2 //用b拷貝構造t1,此時調用的是拷貝建構函式
Destructor is called. 2 //參數b被析構
Default constructor is called. //調用預設的建構函式構造t2
Constructor is called.3 //用3構造參數b
Copy Constructor is called.3 //用b拷貝構造一個臨時對象
Destructor is called. 3 //參數b被析構
The operator "= " is called.3 //調用=操作符初始化t2,此時調用的是賦值操作符
Destructor is called. 3 //臨時對象被析構
Destructor is called. 3 //t2被析構
Destructor is called. 2 //t1被析構
請按任意鍵繼續. . .
另外:
B t1 = fun(2); 和 B t2; t2 = fun(3); 調用的建構函式不同,前面調用的是拷貝建構函式,後面的調用的是“=”操作符的重載,誰能告訴我原因呢 ?