I am learning for my finals and try to overload some operators for my class player. Compiling is fine. But when I try to run the program I get the following error: segmentation fault (core dumped). I never really had this error, because I am learning, but I guess that my programm tried to write on memory, which wasn't allocated. But I have no Idea why.
#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;
}
The overloaded operators works fine if I use them alone. Like p1+p2 works. p3=p1 works aswell. But chaning these operators doesn't work.
Any suggestions?