0
我最近开始使用操作符重载。我想用一个随机整数值来添加名为Player
的类的值,并将这些值存储在另一个Player
类对象中。这些值会在重载函数内查看更改,但是一旦我返回类值就会消失。有人能告诉我我哪里错了吗?如何使用运算符重载添加类变量和int变量?
#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;
}
不要返回对于初学者悬挂参考。 [一个值得彻底阅读的页面](https://stackoverflow.com/questions/4421706/operator-overloading)。 – WhozCraig
这里有很多错误。我会首先在C++中搜索关于运算符重载的文章。 – RyanP
请参阅[运算符重载](http://stackoverflow.com/questions/4421706/operator-overloading)。 –