C++ 从基类调用派生类函数

标签 c++ derived-class

我不确定如何从基类调用派生类函数而不会出现某种错误,这是我尝试使用的代码的框架...

class DiceGame{
public:
    virtual void play(){
        // Trying to call the derived class
        // Knockout's play function in here
        // I've been trying this

        DiceGame *game = new Knockout;
        game->play();

        // But it gives me a memory error
    }

class Knockout : public DiceGame{
    void play(){
        // This has the stuff I want to call
    }

main(){
    DiceGame *game = new DiceGame();
    game->play();
}

我已经尝试过 Knockout 类的前向声明,但这也给了我一个不完整的前向声明错误,有什么建议吗?

最佳答案

class DiceGame{
public:
    virtual void play() = 0;
};

class Knockout : public DiceGame{
public:
    virtual void play() { // Replace "virtual" with "override" here if your compiler supports "override" keyword.
        // This has the stuff I want to call
    }
};

int main()
{
    DiceGame *game = new Knockout();
    game->play();
    return 0;
}

关于C++ 从基类调用派生类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46179338/

相关文章:

c++ - 使用带有引用的手动内存管理?

c++ - Eclipse 作为 Linux 和 Windows 上的 C++ 代码的跨平台 IDE

qt - QWidget 派生类不可见

c++ - 如何在 Spirit Lex 模式中使用斜杠?

c++ - Linux:检查进程是否具有对 C/C++ 文件的读取权限

c++ - 创建在 C++ 结构体中声明的数组 a[1] 的多个实例

c# - 为什么我不能从动态对象访问 Internal/Friend 属性?

java - 父类(super class)和子类解析?

python - 对 argparse 参数解析器进行子类化

c++ - 将从接口(interface)派生的类的实例添加到接口(interface)指针数组