C++物件導向程式設計 筆記2(Class with pointer members)

來源:互聯網
上載者:User

標籤:

二 Class with pointer members(Class String)

1. 測試代碼(使用效果)

int main(){    String s1(),    String s2("hello");          //建構函式    String s3(s1);               //拷貝構造    cout << s3 << endl;    s3 = s2;                     //拷貝賦值    cout << s3 << endl;}

 

2 Big three(三種特殊函數)

class String{public:    String(const char* cstr = 0);    String(const String& str); //參數為相同類型對象的引用,拷貝構造     String& operator=(const String& str); //拷貝賦值    ~String() //解構函式    char* get_c_str() const{        return m_data;    }private:    char* m_data; };

2.1 ctor & dtor(構造與析構)

inlineString::String(const char* cstr = 0){    if(cstr){        m_data = new char[strlen(cstr)+1];        strcpy(m_data,cstr);     }    else{   //未指定長度         m_data = new char[1];        *m_data = ‘\0‘;    }}inlineString::~String(){    delete[] m_data;} 

2.2 Class with pointer members必須有copy ctor(拷貝構造)和copy op(拷貝賦值)

深拷貝與淺拷貝

 

深拷貝:

inlineString::String(const String& str){    m_data = new char[strlen(str.m_data) + 1];  //直接取得另一個對象的private資料                                                //可用友元解釋     strcpy(m_data, str.m_data);}

 

拷貝賦值函數:

思路:若右邊拷貝到左邊,步驟為 清空左邊;分配與右邊相同空間;完成拷貝。

inlineString& String::operator=(const String& str){    if(this == &str){  //檢測自我賦值,不僅僅是效率問題         return *this;  // 如果不檢驗的話,可能造成行為未定義,見解釋    }    delete[] m_data;    // 清除左邊     m_data = new char[ strlen(str.m_data) + 1];//開闢空間     strcpy(m_data, str.m_data); //完成拷貝     return *this} 

 

 

 

總結:有指標變數的類,一定要重新其拷貝構造,拷貝賦值和解構函式!

 

C++物件導向程式設計 筆記2(Class with pointer members)

聯繫我們

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