條款10:令operator=返回一個reference to *this
- <span style="font-size:14px;">int x, y, z;
- x=y=z=15;</span>
編譯器解釋時時這樣的:
- #include<iostream>
- using namespace std;
- class Widget
- {
- public:
- Widget()
- {
- cout<<"Default Ctor"<<endl;
- }
- Widget(const Widget& rhs)
- {
- cout<<"Copy Ctor"<<endl;
- }
- Widget& operator=(const Widget& rhs)
- {
- cout<<"operator="<<endl;
- return *this;
- }
- };
- int main()
- {
- Widget a,b,c;
- a=b=c;
- return 0;
- }
Default Ctor
Default Ctor
operator=
operator=
Default Ctor
Default Ctor
operator=
Copy Ctor
operator=
Copy Ctor
條款11:在operator=中實現“自我賦值”
- class Widget
- {
- public:
- Widget& operator=(const Widget& rhs)
- {
- delete p;
- p=new int(ths.p);
- return *this;
- }
- int *p;
- };
- class Widget
- {
- public:
- Widget& operator=(const Widget& rhs)
- {
- if(this==&rhs)//證同測試
- return *this;
- delete p;
- p=new int(rhs.p);
- return *this;
- }
- int *p;
- };
- class Widget
- {
- public:
- Widget& operator=(const Widget& rhs)
- {
- int tmp=p;//記錄原先內存
- p=new int(rhs.p);
- delete tmp;//釋放原先內存
- return *this;
- }
- int *p;
- };
- class Widget
- {
- public:
- void swap(const Widget& rhs);//交換rhs和this
- Widget& operator=(const Widget& rhs)
- {
- Widget tmp(rhs);//賦值一份數據
- swap(tmp)//交換
- return *this;//臨時變量會自動銷燬
- }
- int *p;
- };
- class Widget
- {
- public:
- void swap(const Widget& rhs);//交換rhs和this
- Widget& operator=(const Widget rhs)
- {
- swap(rhs)
- return *this;
- }
- int *p;
- };
條款12:複製對象時勿忘其每一部分
- class Cutsomer
- {
- public:
- Cutsomer()
- {
- name="nobody";
- }
- Cutsomer(const Cutsomer& rhs)
- :name(rhs.name)
- {
- cout<<"Customer Copy Ctor"<<endl;
- }
- Cutsomer& operator=(const Cutsomer& rhs)
- {
- cout<<"assign operator"<<endl;
- name=rhs.name;
- return *this;
- }
- private:
- string name;
- };
- class Cutsomer
- {
- ……
- private:
- string name;
- string telphone;
- };
- class PriorityCustomer:public Cutsomer
- {
- public:
- PriorityCustomer()
- {
- cout<<"PriorityCustomer Ctor"<<endl;
- }
- PriorityCustomer(const PriorityCustomer& rhs)
- :priority(rhs.priority)
- {
- cout<<"PriorityCustomer Copy Ctor"<<endl;
- }
- PriorityCustomer& operator=(const PriorityCustomer& rhs)
- {
- cout<<"PriorityCustomer assign operator"<<endl;
- priority=rhs.priority;
- return *this;
- }
- private:
- int priority;
- };
- PriorityCustomer(const PriorityCustomer& rhs)
- :Cutsomer(rhs),priority(rhs.priority)
- {
- cout<<"PriorityCustomer Copy Ctor"<<endl;
- }
- PriorityCustomer& operator=(const PriorityCustomer& rhs)
- {
- cout<<"PriorityCustomer assign operator"<<endl;
- Cutsomer::operator=(rhs);
- priority=rhs.priority;
- return *this;
- }
可以發現複製構造函數和賦值操作符有類似的代碼。但是者兩個函數不能相互調用。複製構造函數是構造一個不存在的對象,而賦值操作符是給一個存在的對象重新賦值。消除重複代碼的方法編寫一個private方法,例如void Init()。在這個函數中操作重複代碼。