このプログラムは、ダイナミックな2次元配列ボードがルームクラスでいっぱいのゲームです。各ルームクラスには、4つの異なる子クラスのいずれかを継承するプライベートポインタイベントクラスがあります。私の目標は、各子クラス内でイベントクラスを仮想関数にすることで、継承された子クラスから文字列を返すイベントで純粋な仮想関数を呼び出すことができます。私はSEGのエラーが発生しています。ここに私の簡略化されたコードは次のとおりです。ポインタクラス内の仮想関数を参照するときのsegfault
//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を呼び出すたび、それは仮想関数から文字列を返すために最終的な目標は、部屋内のイベントは、そのような別の何かのためであっても、だろうピットとして、 "ピット"という文字列を返します。で
ありがとうございました!これは理にかなっており、私がしていることがどういうことが間違っているのか分かります。 – Martin