實現賦值操作符要注意的問題

來源:互聯網
上載者:User

實現賦值操作符要注意的問題

* 賦值操作符實現的簡例
CFoo & CFoo::operator=(const CFoo & rhs)

{

  if (this == &rhs)

    return *this;              // 防止自賦值


  // assign to all data members

  // ...


  return *this;                // 返回自身引用

}


* 要防止自身賦值
* 必須對每個成員賦值
* 增加新資料成員時,要同時更新賦值
* 子類賦值函數必須調用父類的賦值函數

derived& derived::operator=(const derived& rhs)

{

  if (this == &rhs) return *this;


  base::operator=(rhs);    // 調用this->base::operator=

  // 子類成員賦值...


  return *this;

}

但如果基類賦值運算子是編譯器產生的,可這樣實現derived::operator=:

derived& derived::operator=(const derived& rhs)

{

  if (this == &rhs) return *this;


  static_cast<base&>(*this) = rhs;      // 對*this的base部分

                                        // 調用operator=

  // ...

  return *this;

}

* 如果不會用到賦值操作,就聲明一個私人賦值函數。

 

2010.12.14 補充: zy498420
指出成員賦值時須小心記憶體流失, 詳見下面的評論.

 

聯繫我們

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