我不确定如何从基类调用派生类函数而不会出现某种错误,这是我尝试使用的代码的框架...
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/