我正在为我的决赛学习并尝试为我的班级选手重载一些操作员。编译很好。但是当我尝试运行该程序时,我收到以下错误: 分段错误(核心转储)。 我从来没有真正遇到过这个错误,因为我正在学习,但我想我的程序试图写入内存,而这个内存并没有被分配。但我不知道为什么。
#include <iostream>
#include "overload.h"
using namespace std;
player::player(int lvl2, int iq2, int s2){
lvl=lvl2;
iq=iq2;
s=s2;
}
player::player(){
lvl=1;
iq=10;
s=10;
}
bool player::maxlvl(){
if(lvl < 100)
return false;
else
return true;
}
void player::lvlup(){
lvl=lvl+1;
iq=iq+3;
s=s+3;
}
void player::skillup(int iq2, int s2){
if(iq2+s2<5){
iq=iq+iq2;
s=s+s2;
}else{
cout << "Not enaugh skillpoints" << endl;
}
}
//operator+ is a friend function defined in the header
player& operator+(const player& lhs, const player& rhs){
player p;
p.lvl = lhs.lvl + rhs.lvl;
p.iq = lhs.iq + rhs.iq;
p.s = lhs.s + rhs.s;
return p;
}
//operator- and operator= are member functions defined in the header
player& player::operator-(const player& rhs){
player p;
p.lvl=this->lvl-rhs.lvl;
p.iq = this->iq + rhs.iq;
p.s = this->s + rhs.s;
return p;
}
player& player::operator=(const player& rhs){
player p;
p.lvl =rhs.lvl;
p.iq=rhs.iq;
p.s=rhs.s;
return p;
}
int main(){
player p1(10,32,24); //creates player with lvl=10, iq=32, s=24
player p2; //creates player with lvl=1, iq=10, s=10
player p3; //creates player with lvl=1, iq=10, s=10
p2.lvlup(); //set values of p2: lvl=2, iq=13, s=13
p3=p1+p2; //should add p1 and p2. And overwrites the values of p3
cout << p1.lvl << " " << p1.iq << " " << p1.s <<endl;
return 0;
}
如果单独使用它们,重载的运算符可以正常工作。 像p1 + p2一样有效。 p3 = p1也适用。但是,操纵这些操作员并不起作用。
有什么建议吗?