+ 1
What is the working of Overloading binary operators.
1.class complex{ 2. float x; 3. float y; 4. public: 5. complex(){} 6. complex(float a, float b){ 7. x = a; y = b; 8. } 9. complex operator+(complex); 10. 11. }; 12.complex complex::operator+(complex c){ 13. complex temp; 14. temp.x=x+c.x; 15. temp.y=y+c.y; 16. return (temp); 17.} 18.int main(){ 19. complex c1,c2,c3; 20. c1=complex(2.2, 4.4); 21. c2=complex(3.3, 5.5); 22. c3=c1+c2; 23.} what happen at line 14 & 15 means what is the value of x&y that time
4 Respostas
+ 2
Ignoring compile errors due to typos, c3.x is 5.5 and c3.y is 9.9 after line 22 because line 14 adds 2.2 & 3.3 together from c1 & c2 and line 15 adds their 4.4 & 5.5 together.
c1+c2 can be thought of as c1.operator+(c2). Therefore, the x & y in those lines are c1.x & c1.y, while c is c2.
+ 3
c1.operator+(c2) makes c1 as this in the function. x & y are this.x and this.y. The this is optional.
+ 3
ok thanks.
+ 2
John Wells you mean by default x & y is treated as c1.x & c1.y?