条款15:令operator=传回"*this的reference"

本文详细介绍了C++中赋值运算符的工作原理及常见错误。解释了如何正确实现赋值运算符以支持链式赋值,并给出了具体的代码示例。
1,assignment动作可以串连在一起.
string w, x, y, z;
w = x = y = z = "Hello";
赋值使用右结合律,上述行动串被解析成这样:
w = (x = (y = (z = "Hello")));
或是:
w.operator=(x.operator=(y.operator=(z.operator=("Hello"))));
可见:y.operator=的引数就是前次调用operator=后的传回值.

2,常犯的错误:
(1)令opertor=传回void,它会妨碍assignment动作串链的形成.
(2)令opertor=传回一个const对象的引用.
如:const Widget& operator=(const Widget& rhs);
考虑下面的情况:
Widget w1, w2, w3;
(w1 = w2) = w3; //给const赋值
将导致段错误.

3,总结:你没有什么选择.
assignment总是传回一个reference,指向其左侧引数,即:*this.
填充下面这个程序中所有出现// TODO: fill the code这个任务的地方#include <iostream> #include <cstring> #include "ourstring.h" #include "strlib.h" using namespace std; OurString::OurString(){ // TODO: fill the code } OurString::OurString(const char *str){ // TODO: fill the code } OurString::OurString(const OurString &dstr){ // TODO: fill the code } OurString::~OurString(){ // TODO: fill the code } string OurString::toString() const{ // TODO: fill the code } OurString OurString::subStr(unsigned int start, unsigned int n) const{ // TODO: fill the code } bool OurString::operator > (const OurString &dstr) const{ // TODO: fill the code } bool OurString::operator < (const OurString &dstr) const{ // TODO: fill the code } bool OurString::operator == (const OurString &dstr) const{ // TODO: fill the code } unsigned int OurString::length () const{ // TODO: fill the code } const OurString& OurString::operator = (const OurString &dstr){ // TODO: fill the code } const OurString& OurString::operator = (const char *str){ // TODO: fill the code } char& OurString::operator[](int index){ // TODO: fill the code } const OurString OurString::operator + (const OurString &dstr) const{ // TODO: fill the code } const OurString OurString::operator + (const char *str) const{ // TODO: fill the code } const OurString& OurString::operator += (const OurString &dstr){ // TODO: fill the code } const OurString& OurString::operator += (const char *str){ // TODO: fill the code } ostream & operator<<(ostream &os, const OurString &dstr){ // TODO: fill the code } istream & operator>>(istream &is, OurString &dstr){ // TODO: fill the code }
05-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值