<C++ - 拷貝構造> 2018-01-12

來源:互聯網
上載者:User

標籤:names   ret   實參   post   關於   釋放記憶體   etc   指標   body   

 

#include <iostream>using namespace std;/*    回顧上節的內容:        1.構造和析構        2.new  delete        3.delete[]    新的知識        1.拷貝構造 ->建構函式  函數名和類名相同  沒有傳回值            定義: 用拷貝的方式構造對象  調用拷貝構造                參數為 該類對象的建構函式        關於引用:            1.拷貝構造  參數必須為引用            2.加引用*///========================================類函數======================================class A{private:    char *arr;   // 指標    int x;public:    A()        // 參建構函式    沒有傳回值  自動調用    {        cout << "調用無參建構函式" << endl;        this->arr = NULL;    // 給對象中的arr賦值        this->x = 0;    }        A(int x)    {        cout << "調用有參建構函式" << endl;        this->arr = new char[x];    // 申請記憶體        this->x = x;    }    A(A & other)  // 拷貝構造           {        /**        參數是同類型的對象   other形參 -->相當是 sum           shis指向當前對象相當於 (23)的fnu           other拷貝的是sum --> 調用拷貝建構函式  所以必須加引用        拷貝 -->內容拷貝  直接用參數  定義一個新的形參        引用  取別名 不全定義新的形參        */        cout << "拷貝建構函式" << endl;        this->arr = other.arr;        this->x = other.x;    }    ~A()    // 解構函式  --> 沒有傳回值  沒有參數  自動調用    {        cout << "調用解構函式" << endl;        if (arr != NULL)        {            delete[]arr;   // 釋放記憶體            arr = NULL;        }    }    void mamied(A other)    {        cout << "是否婚配" << endl;    }};/**    new  delete  申請對象的記憶體空間的時候 調用對象的構造/解構函式    delete[]  調用每個對象的解構函式*///==========================================新內容====================================int main(){    {        A sum;                // 定義一個對象sum   在棧區 (調用無參構造)        A fnu(sum);            // 調用拷貝構造   (23)        sum.mamied(fnu);    // 函數 傳參  實參 -->形參賦值  形參拷貝實參    }        getchar();    return 0;}

 

<C++ - 拷貝構造> 2018-01-12

聯繫我們

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