我认为我应该从简化类结构开始,以便更好地解释我的问题,我怀疑这可能只是对使用虚拟的误解。
我有:
class Controller{
..
virtual void InitialiseController(){ //std::cout confirms this is running }
..
}
class AIController : public Controller{
..
virtual void InitialiseController(){ //some logic here }
..
}
class ComController : public AIController{
..
virtual void InitialiseController(){ //actually the same logic as parent }
..
}
我的对象Snake有一个指向Controller
(Controller* _controller)
的指针。当我调用snake.initialise(..)
方法时,我向它传递了一个新的ComController对象,该对象随后将蛇_controller设置为等于新的ComController。我知道该过程可以成功进行。但是,当我随后调用
_controller.InitialiseController();
时,调试器将程序步骤显示到基类Controller的InitialiseContoller的空白实现中。我知道我可能过于简化了,您可能无法提供帮助,但是我认为也许我对整个概念不了解,这是逻辑错误,而不是类型错误,并且想检查一下。
附加代码:
_player2->Initialise(_gameProperties, &_fruitManager, new ComController(_player2), _player1);
介入..
void Snake::Initialise(
GamePropertiesManager* gpm, FruitManager* fm, Controller* control, Snake* opposingSnake)
{
_game = gpm;
_fruitManager = fm;
_controller = control;
_opposition = opposingSnake;
if(_controller){
///Bunch of stuff in here runs just fine
// This primarily serves to ensure that a ComControllers timer is started, but other controllers might wish to override initialise later
_controller->IntialiseController();
}
}
最佳答案
我确实没有发现您所做的任何事情出问题(至少就理解和使用虚拟方法而言)。
这是一个完整的例子。请与您的代码进行比较。
#include <stdio.h>
class Controller{
public:
virtual void InitialiseController(){
printf ("base class controller...\n");
}
};
class AIController : public Controller{
public:
virtual void InitialiseController(){
printf ("AIController subclass controller...\n");
}
};
class ComController : public AIController{
public:
virtual void InitialiseController(){
printf ("ComController subclass controller...\n");
}
};
int main (int argc, char *argv[])
{
Controller *myController = new ComController ();
myController->InitialiseController ();
return 0;
}
编译:
g++ -Wall -pedantic -o tmp tmp.cpp
执行:
ComController subclass controller...
关于c++ - 多态性误解/重新定义的虚函数不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10339612/