operator += problem...

Why gives me 4 and not 10? Any idea why is that?

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
struct a
{
    int i;
    a() {};
    a(int ii)
    {
        i=ii;
    };
};

a operator +=(a i,a j)
{
    a x;
    x.i=i.i+j.i;
return x;
}

int main()
{
    a k1(4);
    a k2(6);
    k1+=k2;
    cout << k1.i << endl;
    return 0;
}
Last edited on
You need to pass and return by reference, not by copy.
You have implemented the semantics of operator+

You need to modify the first parameter.
I am trying
a &operator +=(a &i,a &j) or a operator +=(a &i,a &j)
but resaul is 4.

Last edited on
Modifying only the prototype of the function isn't enough.

1
2
3
4
5
a& operator+=(a& i, a j)
{
    i.i += j.i ;
    return i;
}
Thank's, that work fine.
Your operator+= takes it's arguments by value (copy) and returns a copy so when you type k1+=k2 you copy k1 and k2 and return a copy, that you don't capture (put into a variable). This means that k1 and k2 haven't been modified since you passed by value, which results in k1 retaining the same value.
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
30
31
32
33
34
35
#include <iostream>
 
class a
{
private:
// int i;
public:
    int i;
    a() {}//;
    a(int ii)  { i=ii; }//;
};

a operator + (const a &i, const a &j)
{
    a x;
    x.i= i.i + j.i;
return x;
}

void operator += ( a &i, const a &j) //non-member function, CAN'T access i if private.
{
	i.i += j.i;
return;
}

int main()
{
    a k1(4);
    a k2(6);

	k1 += k2;
	std::cout << k1.i << "\n\n";  //10

return 0;
}
Thank you very mutch.
Worka fine ...
Topic archived. No new replies allowed.