1. 为了支持形如“a=b=c”的连锁形式,最好令operator=返回一个reference to *this.
2. 如果类中含有用于指向堆内存的指针,那么赋值操作符就要注意自我赋值的问题,
//
// main.cpp
// 条款10:令operator=返回一个reference to *this
//
// Created by 于磊 on 2018/6/24.
// Copyright © 2018 于磊. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
class Widget {
public:
Widget(const std::string &str, int money) : componet(str), money(money) {
}
Widget &operator=(const Widget &rhs) {
componet = rhs.componet;
return *this;
}
Widget &operator+=(const Widget &rhs) {
money += rhs.money;
return *this;
}
std::string componet = "letf";
int money = 0;
};
int main(int argc, const char *argv[]) {
Widget widget_you("you", 10);
Widget widget_me("me", 2);
cout << widget_you.componet << " and " << widget_me.componet << " with " << widget_me.money << " " << widget_you.money << endl;
widget_me = widget_you;
widget_me += widget_you;
cout << widget_you.componet << " and " << widget_me.componet << " with " << widget_me.money << " " << widget_you.money << endl;
return 0;
}