我正在为我的C ++课程编写一个类似于Tomogotchi的简单游戏,一开始运行情况很好,但是在添加了更多内容之后,在main尚未运行之前就出现了分割错误。因此,我使用 gdp ./a.out core 命令检查了引起此问题的行。这样做表明我的头等舱声明的开头引起了分段错误。这是该类的代码,它非常简单:
class Creature{
private:
int hungLvl;
int borLvl;
string name;
int happyCount;
public:
Creature(){
hungLvl=rand()%6;
borLvl=rand()%6;
happyCount=0;
}
void listen(){
cout<<"My hunger level is: "<<hungLvl<<endl;
cout<<"My boredom level is: "<<borLvl<<endl;
cout<<"I am feeling "<< mood()<<endl;
}
string mood(){
if(borLvl>15){
return "MAD!";
}
else if(borLvl>10&&borLvl<14){
return "Frustrated";
}
else if(borLvl>5&&borLvl<9){
return "OK";
}
else if(borLvl>0&&borLvl<4){
return "Happy!";
}
else{
return " ";
}
}
virtual void shout(){
cout<<"base shout"<<endl;
}
void setName(string s){
name=s;
}
string getName(){
return name;
}
int getBor(){
return borLvl;
}
void incLvls(){
borLvl++;
hungLvl++;
}
void happyInc(){
happyCount++;
}
};