深入C++中建構函式、拷貝建構函式、賦值操作符、解構函式的調用過程總結

來源:互聯網
上載者:User

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); 調用的建構函式不同,前面調用的是拷貝建構函式,後面的調用的是“=”操作符的重載,誰能告訴我原因呢 ?

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.