建構函式、複製建構函式、解構函式混合使用總結

來源:互聯網
上載者:User
一、用法

建構函式的用法:類的聲明、定義與初始化

複製建構函式的用法:複製建構函式總結

2.一些混合使用的例子1.關於強制類型轉換
class A{int x;public:A(int i):x(i){cout<<"construct     "<<this<<endl;}A(const A& a){x = a.x;cout<<"copy     "<<this<<endl;}~A(){cout<<"delete     "<<this<<endl;}void operator=(const A& a){x = a.x;cout<<"=     "<<this<<endl;}void get(){cout<<x<<endl;}void set(int i){x = i;}};int main(){A a(99), b(35);a.get();a = 1000; //隱式的強制類型轉換 + 賦值a.get();a = A(2); //顯式的強制類型轉換 + 賦值a.get();a = b;    //賦值a.get();return 0;}

輸出:
construct     0012FF38     //a的構造
construct     0012FF34     //b的構造
99
construct     0012FF30     //臨時對象的構造
=     0012FF38             //賦值
delete     0012FF30        //臨時對象的析構
1000
construct     0012FF2C     //臨時對象的構造
=     0012FF38             //賦值
delete     0012FF2C        //臨時對象的析構
2
=     0012FF38             //賦值
35
delete     0012FF34        //
delete     0012FF38        //
解釋:不管是顯示類型轉換還是隱式類型轉換,都有以下一些共同點:
1)先構造一個臨時對象,把臨時對象賦值給目標,然後析構臨時對象
2)由於要構造一個臨時對象,必須要有只帶一個參數的建構函式
3)由於要用到賦值函數,當類中有指標成員時,要定義自己的複製控制函數2.兩個例子對比看

class A{public:A(){cout<<"construct     "<<this<<endl;}A(const A& a){cout<<"copy     "<<this<<endl;}~A(){cout<<"delete     "<<this<<endl;}void operator=(const A& a){cout<<"=     "<<this<<endl;}A Test(){return *this;}};int main(){A a;A b = a.Test(); return 0;}

輸出:
construct     0012FF38  //a的構造
copy     0012FF34       //b的構造(傳回值的構造)
delete     0012FF34     //b的析構(傳回值的析構)
delete     0012FF38     //a的析構
解釋:
L13中,b是傳回值的別名,傳回值是*this的複製,*this就是a
因此:b = 傳回值 = *this的副本 = a的副本

class A{public:A(){cout<<"construct     "<<this<<endl;}A(const A& a){cout<<"copy     "<<this<<endl;}~A(){cout<<"delete     "<<this<<endl;}void operator=(const A& a){cout<<"=     "<<this<<endl;}A Test(){return *this;}};int main(){A a, b;b = a.Test(); return 0;}

輸出:
construct     0012FF38   //a的構造
construct     0012FF34   //b的構造
copy     0012FF30        //傳回值的構造
=     0012FF34           //把傳回值的內容賦值給b
delete     0012FF30      //傳回值的析構
delete     0012FF34      //b的析構
delete     0012FF38      //a的析構
解釋:
L13中,把傳回值的內容賦值給b,然後傳回值析構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.