Assignment operators should generally return *this by reference. This means that they adhere to the same convention used by the built-in types by allowing assignment to be used as an expression rather than simply as a statement. This allows assignment to be cascaded into larger expressions. An example follows. #include <iostream> using namespace std; class Fred { public: Fred(int i=3) throw(); Fred& operator= (const Fred& x) throw(); friend int operator== (const Fred& a, const Fred& b) throw(); protected: int i_; }; Fred::Fred(int i) throw() : i_(i) { } Fred& Fred::operator= (const Fred& x) throw() { i_ = x.i_; return *this; } int operator== (const Fred& a, const Fred& b) throw() { return a.i_ == b.i_; } int main() { Fred x, y, z; x = y = 5; <-- 1 if ((z = x) == y) <-- 2 cout << "z (which was assigned from x) is equal to y\n"; }
|