C++學習體會--引用方式複製類對象

來源:互聯網
上載者:User

標籤:定義   code   系統   char*   cal   值傳遞   資源   bsp   cbo   

C++學習體會--引用方式複製類對象

引用的重要性實際體現在函數的形參和函數的傳回值。一般引用也只是出現在這兩個地方。

引用方式的好處,如果是體現在形參,在使用函數的時候,實參必定會初始化形參,如果不加引用,系統會建立實參的副本將值傳遞給形參,這樣會造成資源額外的佔用。為了節省資源的佔用,通過一種引用的方式,達到這個效果,因為引用知識將實參的地址給了形參,處理形參,如同處理實參。

 

下面將給出程式使用的例子:引用的重要性體現在形參上

 

#include <iostream>using namespace std;class CBox{private:    double m_Length;    double m_Width;    double m_Height;public:    CBox(double lv, double wv, double hv) : m_Length{ lv }, m_Width{ wv }, m_Height{ hv }    {        cout << "Constrcurtor called." << endl;    }    CBox(const CBox &initB) :CBox{ initB.m_Length, initB.m_Width, initB.m_Height }{            cout << " refrence  called" << endl;    }    double volume()    {        return m_Length*m_Height*m_Width;    }};int _tmain(int argc, _TCHAR* argv[]){    CBox box1( 10.0, 10.0, 10.0 );    CBox mybox(box1);// mybox{box1};相同         cout << "Volume of box1=" << box1.volume() << endl;    cout << "Volume of mybox=" << mybox.volume() << endl;        return 0;}

 

結果:

 分析:
    CBox box1( 10.0, 10.0, 10.0 );    CBox mybox(box1);
1.這兩句的類定義,會自動調用建構函式,在類聲明中可以看到每次調用建構函式時,會顯示Constrcurtor called .
2.因為定義mybox()以box1作為實參,不是為box1棄置站台,而是通過引用的方式傳遞給形參,成功通過引用的方式時,將會出現refrence called

 

C++學習體會--引用方式複製類對象

聯繫我們

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