c++ - Operator Overloading -
i'm confused topic regarding operator overloading. see following code:
#include <iostream>; class vectors { public: int x, y; vectors() {}; vectors(int a,int b) { x = a, y = b; } vectors operator+(vectors aso) { vectors brandnew; std::cout << "aso x " << aso.x << std::endl; std::cout << "aso y " << aso.y << std::endl; brandnew.x = brandnew.x + aso.x; brandnew.y = brandnew.y + aso.y; return (brandnew); }; }; int main() { vectors v1(2,3); vectors v2(4,5); vectors v3; v3 = v1 + v2; std::cout << "vector v3 x : " << v3.x << std::endl; std::cout << "vector v3 y : " << v3.y << std::endl; }
when print aso.x, y gives me 4 , 5. want add both v1 , v2; meaning x of v1 , v2, , y of v1 , v2. then, pass vectors object , return object.
how accomplish that, given have above?
you meant
vectors operator+(const vectors& aso) { vectors brandnew; std::cout << "aso x " << aso.x << std::endl; std::cout << "aso y " << aso.y << std::endl; brandnew.x = x + aso.x; brandnew.y = y + aso.y; return (brandnew); };
or
vectors operator+(const vectors& aso) { vectors brandnew(x + aso.x, y + aso.y); std::cout << "aso x " << aso.x << std::endl; std::cout << "aso y " << aso.y << std::endl; return (brandnew); };
as comment
but if there three.
chain operators like
int main() { vectors v1(2,3); vectors v2(4,5); vectors v3(7,11); vectors v4; v4 = v1 + v2 + v3; std::cout << "vector v4 x : " << v4.x << std::endl; std::cout << "vector v4 x : " << v4.y << std::endl; }
see live demo
Comments
Post a Comment