我不确定如何从基类调用派生类函数而不会出现某种错误,这里是我尝试使用的代码的骨架... < / p>
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类声明,但是这给了我一个不完整的前向声明错误,有什么建议吗?
答案 0 :(得分:5)
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;
}