c++ - why should i return reference when i compare three objects? -
i tring learn operator overloading , dont somthing. when do:
class point { public: void show(){ cout << "the point is(" << _x << ", " << _y << ")" << endl;} void print(){ _x = 1; _y = 1; } void operator+=(const point &other){ _x = other._x + 100; _y = other._y + 100; } private: int _x; int _y; }; int main() { point p1; point p2; p1 +=p2; p2.show(); getchar(); }
its work. when change to:
point p1; point p1; point p2; point p3; p1 +=p2 +=p3;
its doesnt , need return (*this). why it? if can explain me greatfull.. :)
the reason need return reference here p2 +=p3
not evaluate p2
after p3
has been added it. evaluate return value of operater+=
of point
void
. cannot add void
p1
error.
another way of looking @ p2 +=p3
p2.operator+=(p3)
. here can see not p2
instead p2.operator+=(p3)
returns.
this why return reference. allows chain results trying do. if not return reference have break chain.
Comments
Post a Comment