该程序是一个游戏,其中动态2d阵列板充满了房间类别。每个房间类都有一个专用的指针事件类,它将继承四个不同的子类之一。我的目标是使虚拟函数成为每个子类中的事件类,以便在事件中调用纯虚拟函数,该函数将从继承的子类中返回一个字符串。我遇到了段错误错误。这是我的简化代码:
//in game class
board[1][1].set_bat();
board[1][1].get_message();
//room.h
class room {
private:
event *ev; //here, each room class is given an event class pointer
public:
void set_bat();
void get_message();
};
//in room.cpp
void room::set_bat(){ //here, the event pointer is set to one of its child classes.
bats x;
ev = &x;
//ev->message(); if the message func is called here, it return "bats" correctly,
}
void room::get_message(){ //calling this, is where the error occurs
ev->message();
}
//in event.h
class event {
public:
virtual void message() = 0;
};
//in bats.h
class bats: public event{
public:
void message();
};
//in bats.cpp
void bats::message(){
cout<<"bats"<<endl;
}
最终目标是,每当我在游戏类中调用get_message时,它将从虚拟函数返回字符串,即使房间内发生的事件是针对诸如pit之类的东西,它也将返回字符串“ pit” 。
最佳答案
在:
void room::set_bat(){ //here, the event pointer is set to one of its child classes.
bats x;
ev = &x;
//ev->message(); if the message func is called here, it return "bats" correctly,
}
您正在返回一个指向局部变量的指针。函数返回时,此变量超出范围,因此
ev
现在指向垃圾。您应该使用
new
分配指针:void room::set_bat(){
ev = new bats();
}
这也意味着您应该为调用
room
的delete ev
类定义一个析构函数:class room {
private:
event *ev; //here, each room class is given an event class pointer
public:
void set_bat();
void get_message();
~room() { delete ev; } // ADDED
};
关于c++ - 在指针类中引用虚拟函数时出现段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37368858/