国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

深入C++中構造函數、拷貝構造函數、賦值操作符、析構函數的調用過程總結

2020-01-26 16:04:07
字體:
來源:轉載
供稿:網友
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);  調用的構造函數不同,前面調用的是拷貝構造函數,后面的調用的是“=”操作符的重載,誰能告訴我原因呢 ?
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 酒泉市| 青冈县| 澄城县| 石门县| 安岳县| 盐津县| 金溪县| 石台县| 鲜城| 南乐县| 山丹县| 平舆县| 松潘县| 南溪县| 周至县| 宝鸡市| 惠州市| 郧西县| 平阴县| 青田县| 丰原市| 玛多县| 仁寿县| 新民市| 梓潼县| 米易县| 同德县| 普洱| 沈阳市| 察哈| 山东| 五指山市| 吉首市| 达州市| 莆田市| 建平县| 淮南市| 信阳市| 北辰区| 三明市| 乐平市|