473,320 Members | 1,982 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

'+=': function as left operand error

I'm 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. the code in my class cpp is
---------------------------------------------------------
Expand|Select|Wrap|Line Numbers
  1. player::player()
  2. {
  3.     points = 1000;
  4.     name = "ABC";
  5.     kills = 0;
  6. }
  7.  
  8. player::player(int a)
  9. {
  10.     y = a;
  11. }
  12.  
  13. int player::getPoints()
  14. {
  15.     return points;
  16. }
  17.  
  18. int player::operator+=(player &tmp)
  19. {
  20.  
  21.     points += tmp.y;
  22.  
  23.     return points;
  24. }
---------------------------------------------------------
and in my source:
---------------------------------------------------------
Expand|Select|Wrap|Line Numbers
  1.     a.getPoints += 1000;
  2.     cout << a.getName() << " has killed: " << a.getKills() << " and have: " << a.getPoints() << " points" << endl;
---------------------------------------------------------
Nov 16 '16 #1
1 1189
weaknessforcats
9,208 Expert Mod 8TB
There is no member y in your player class. So tmp.y will never compile.

When you say += for as player object do you mean to only increment the points member? If so this is not good because += is to operate on all member of your class. The operator+= has a player& argument.

Do you mean to add points to your player object:

Expand|Select|Wrap|Line Numbers
  1. int player::operator+=(int x)
  2.  points += x;
  3.  
  4. return points;
  5. }
This should let you code:

player obj;

obj+= 25;
Nov 17 '16 #2

Sign in to post your reply or Sign up for a free account.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.