简体   繁体   English

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

[英]C++ Calling a derived class function from the base class

I'm not sure how to call a derived class function from the base class without getting some sort of error, here's a skeleton of the code I'm trying to work with... 我不确定如何在不出现某种错误的情况下从基类调用派生类函数,这是我尝试使用的代码框架...

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

I have tried forward declaration of the Knockout class, but that gives me an incomplete forward declaration error as well, any advice? 我已经尝试了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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM