By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,515 Members | 1,363 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,515 IT Pros & Developers. It's quick & easy.

'+=': function as left operand error

P: 1
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
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
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

Post your reply

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