Effective C++ Item 10 令operator= 返回一个reference to *this
2014-10-28 16:42
525 查看
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
经验:令赋值(assignment)操作符返回一个reference to *this --》 这样可以实现级联赋值
示例:
[cpp] view
plaincopy
#include <iostream>
#include <string>
using namespace std;
class Widget{
public:
Widget(int v):value(v){}
Widget& operator=(const Widget &rhs){
this->value = rhs.value;
return *this; //返回左侧对象
}
int getValue() const {return this->value;}
private:
int value;
};
int main(){
Widget w1(1);
Widget w2(2);
Widget w3(3);
w3 = w2 = w1;
cout << w3.getValue() << endl;
system("pause");
}
输出:
1
解析:
令operator=,opertor+= 返回一个referenceto *this可以实现级联式(casading)的赋值操作
经验:令赋值(assignment)操作符返回一个reference to *this --》 这样可以实现级联赋值
示例:
[cpp] view
plaincopy
#include <iostream>
#include <string>
using namespace std;
class Widget{
public:
Widget(int v):value(v){}
Widget& operator=(const Widget &rhs){
this->value = rhs.value;
return *this; //返回左侧对象
}
int getValue() const {return this->value;}
private:
int value;
};
int main(){
Widget w1(1);
Widget w2(2);
Widget w3(3);
w3 = w2 = w1;
cout << w3.getValue() << endl;
system("pause");
}
输出:
1
解析:
令operator=,opertor+= 返回一个referenceto *this可以实现级联式(casading)的赋值操作
相关文章推荐
- Effective C++ Item 10 令operator= 返回一个reference to *this
- Effective C++——》条款10:令operator=返回一个reference to *this
- [翻译] Effective C++, 3rd Edition, Item 10: 让 assignment operators(赋值运算符)返回一个 reference to *this(引向 *this 的引用)
- effective c++ 令operator=返回一个reference to *this
- Effective C++ Item 10,11 Have assignment operators return a reference to *this Handle assignment to self in operator =
- 读书笔记_Effective_C++_条款十:令operator=返回一个reference to *this
- 条款10 令operator=返回一个 reference to *this
- 条款10:令operator=返回一个reference to *this
- 条款10:令operator= 返回一个reference to *this
- 条款10:令operator=返回一个reference to *this(Have assignment operators return a reference to *this.)
- Effective C++ -----条款10: 令operator=返回一个reference to *this
- effective C++ 条款 10:operator= 返回一个reference to *this
- 条款10:令operator=返回一个reference to *this
- 条款10:令operator=返回一个reference to * this(Have assignment operators return a reference to *this)
- 条款10:令operator=返回一个reference to * this
- Effective C++ 条款10解读: 令operator= 返回一个reference to *this
- 《Effective C++》学习笔记条款10 令operator= 返回一个reference to *this
- 条款10:令operator=返回一个reference to *this
- 条款10:令operator = 返回一个reference to *this
- 条款10:令operator= 返回一个reference to *this