'+=': function as left operand error

Im trying to make a operator overload for '+=' where I will use it to add a int value to a class called "player" to its private int "points". I'm new to this kind of stuff and I'm pretty bad at c++ overall. I've tried several things but I can't get it to work.

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
  the code in my class cpp is
player::player()
{
points = 1000;
name = "ABC";
kills = 0;
}

player::player(int a)
{
y = a;
}

int player::getPoints()
{
return points;
}

int player::operator+=(player &tmp)
{

points += tmp.y;

return points;
}
---------------------------------------------------------
and in my source:
---------------------------------------------------------
a.getPoints += 1000;
cout << a.getName() << " has killed: " << a.getKills() << " and have: " << a.getPoints() << " points" << endl;
---------------------------------------------------------
a += 1000;
"no operator "+=" matches these operands" error message when I write "a += 1000;"
You're going to need to provide more context than incomplete code snippets and partial error messages.

That may be the result of not being const correct. A non-const reference won't bind to a temporary.

1
2
3
4
5
6
7
int player::operator+=(player &tmp)
{

points += tmp.y;

return points;
}

Should probably be:
1
2
3
4
5
6
player& player::operator+=(const player &tmp)
{
    points += tmp.y;

    return *this;
}

in order to conform with common expectations.

Last edited on
oh my god, IT ACTUALLY WORKS! :D
thank you A LOT stranger, now I can finally send this in to my teacher!
Topic archived. No new replies allowed.