Question about overload operators "<<" and "+"

When I was overload operators "<<" and "+",I thought it would be print '13,20',but why print '20,20'?
This is code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;
class Test
{
public:
	Test(int _a){a = _a;}
	Test(){}
	Test& operator+(const Test& t1){
		*this += t1;
		return *this;
	}
	Test& operator+=(const Test& t1){
		this->a += t1.a;
		return *this;
	}
	friend ostream& operator << (ostream& os,const Test& t){
		os<<t.a<<endl;
		return os;
	}
private:
	int a;
};
int main(void)
{	
	Test t1(6);
	Test t2(7);
	cout << t1 + t2 << t1 + t2;
	return 0;
}
I assume it is the order of priority of operations. All + are done first, then all << afterwards.

After the first +: t1 holds 13, t2 holds 7.

After the second +: t1 holds 20, t2 holds 7.

THEN it starts doing the << operations.


Incidentally, if I saw t1+t2 I would usually expect t1 and t2 themselves to be unchanged and the answer put in a new variable. Returning *this means changing t1 itself, and that is very unnatural. Consider returning a new object of class Test instead.
Your operator+ should not change the operands, but return a new Test object with the sum of the operands.

1
2
3
4
5
6
	
Test operator+(const Test& t1) 
{
      Test t = a + t1.a;
      return t;
}


This result in the expected output of:
13
13
Last edited on
Topic archived. No new replies allowed.