今天在看《Effective C++》的Item 10时,书中说道,赋值操作符需要返回的是对*this的引用。
例如:
class Widget { public: ... Widget& operator += (const Widget& rhs) { ... return *this; } Widget& operator = (const Widget& rhs) { ... return *this; } };
因此,我也尝试着重载了一下其他操作符,发现上面的条款只是对操作符 -= += = *= /= 这些包含赋值操作符。而对于+ - * / 这些操作符则不能按照以上条款!
class myint { public: myint(int i = 0): _i(i) { } ~myint() { } myint& operator=(const myint& rhs) { _i = rhs._i; return *this; } //return myint, it is a temp var myint operator+(const myint& rhs) { myint temp; temp._i = _i + rhs._i; return temp; } myint& operator+=(const myint& rhs) { _i += rhs._i; return *this; } myint operator-(const myint& rhs) { myint temp; temp._i = _i - rhs._i; return temp; } myint& operator-=(const myint& rhs) { _i = _i - rhs._i; return *this; } myint operator*(const myint& rhs) { myint temp; temp._i = _i * rhs._i; return temp; } void result() { cout<<_i<<endl; } private: int _i; };