0

I have recently started working with Operator Overloading. I wanted to add the values of a class named Player with a random integer value and store the values in another Player class object. The values do look changes inside the overloaded function, but disappear once I return the class value. Can someone tell me where I am going wrong here?

#include <iostream>
using namespace std;

 class Player{
  int runs,reps;
  public:
  Player(int r,int rep){
      runs = r;
      reps = rep;
  }
  Player &operator+(int i){
      Player p(1,1);
     // cout<<"hi"<<this->runs<<endl;
      p.runs = this->runs + i;
     // cout<<"hi"<<p.runs<<endl;
      p.reps = this->reps + i;
     // cout<<"hi"<<p.reps<<endl;
      return p;
  }

  void showme(){
      cout<<runs<<"\t"<<reps<<"\t"<<endl;
  }
};
int main() {
    Player t(23,34),p(1,1);
    int i;
    i = 3;
    p = t + i;
    p.showme();
    return 0;
}
Rama
  • 3,222
  • 2
  • 11
  • 26
  • 2
    Don't return a dangling reference for starters. [A page worthy of thorough reading](https://stackoverflow.com/questions/4421706/operator-overloading). – WhozCraig Feb 16 '17 at 19:06
  • There is a lot wrong here. I'd search for an article on operator overloading in C++ first. – RyanP Feb 16 '17 at 19:06
  • 1
    See [Operator Overloading](http://stackoverflow.com/questions/4421706/operator-overloading). – R Sahu Feb 16 '17 at 19:08

1 Answers1

3

You may do

Player& operator+=(int i) {
      runs += i;
      reps += i;
      return *this;
}

friend Player operator+(Player p, int i) {
      return p += i;
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302