2016-05-21 5 views
1

このプログラムは、ダイナミックな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を呼び出すたび、それは仮想関数から文字列を返すために最終的な目標は、部屋内のイベントは、そのような別の何かのためであっても、だろうピットとして、 "ピット"という文字列を返します。で

答えて

0

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(); 
} 

これはまた、あなたがdelete evを呼び出して、あなたのroomクラスのデストラクタを定義する必要があります意味:

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 
}; 
+0

ありがとうございました!これは理にかなっており、私がしていることがどういうことが間違っているのか分かります。 – Martin