I'm trying to understand why the assignment operator must return a reference.I understood why it shouldn't return void,because of the chained operations.
But this two codes work exactly the same:
So what's the difference,why should it return a reference ?
But this two codes work exactly the same:
#include <iostream> using namespace std; class fail{ int a; public: void display() { cout<<a<<" "; } fail (){} fail(int n) { a=n;} fail operator= (const fail& rhs){ // here difference a=rhs.a; return *this; } }; int main() { fail one(2); fail two; fail three(9); two=one=three=314; one.display(); two.display(); three.display(); cin.ignore(); return 0; }
#include <iostream> using namespace std; class fail{ int a; public: void display() { cout<<a<<" "; } fail (){} fail(int n) { a=n;} fail& operator= (const fail& rhs){ //here difference a=rhs.a; return *this; } }; int main() { fail one(2); fail two; fail three(9); two=one=three=314; one.display(); two.display(); three.display(); cin.ignore(); return 0; }
So what's the difference,why should it return a reference ?