【问题标题】:segfault when referencing virtual function within pointer class在指针类中引用虚函数时出现段错误
【发布时间】:2016-09-19 00:39:44
【问题描述】:

这个程序是一个游戏,其中一个动态二维阵列板充满了房间类。每个房间类都有一个私有指针事件类,它将继承四个不同的子类之一。我的目标是让每个子类中的事件类都有虚函数,这样我就可以在事件中调用一个纯虚函数,它会从继承的子类返回一个字符串。我收到一个段错误错误。这是我的简化代码:

//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 时,它​​都会从虚函数返回字符串,即使房间内的事件是针对不同的东西(例如坑),它会返回字符串“坑”。

【问题讨论】:

    标签: c++ pointers inheritance polymorphism virtual-functions


    【解决方案1】:

    在:

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

    【讨论】:

    • 谢谢!这是有道理的,我可以看到我做错了什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2020-12-27
    • 2021-10-24
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多