-1

我有一个名为“Game”的类,具有原型函数“Update”和“Draw”,但它们没有定义。由继承“游戏”对象的对象来覆盖它们。这可能吗?

“Game.h”的内容

class Game // does it have to abstract/virtual?
{
    public:
    //General stuff for all games here
}

void Update(Game *game) = 0; // or make it virtual in someway

“MyGame.h”的内容

#include "Game.h"

class MyGame : public Game
{
    public:
    // General stuff for my game
}

void Update(MyGame *game);

// “MyGame.cpp”的内容

#include "MyGame.h"

void Update(MyGame *game) // does it have to be overriden/overloaded?
{
}

// “GameManager.h”的内容

#include "Game.h"

class GameManager
{
    public:
    Game *game;
}

void Update(GameManager *manager);

// “GameManager.cpp”的内容

#include "Game.h"

void Update(GameManager *manager)
{
    Update(manager->game);
}

关键是最后一个方法:为什么当GameManager的Game object = MyGame而不是Game时,GameManager不能调用MyGame Update()方法?

4

1 回答 1

2

在基类中定义DrawUpdate作为方法。virtualGame

class Game
{
public:
   virtual void Draw() {};
};

class MyGame : public Game
{
public:
   virtual void Draw() {}
};

void callDraw(Game* game) 
{
   game->Draw();
}

//...

Game* game = new MyGame;
callDraw(game);

最后一次调用将调用该方法,MyGame尽管它是在Game指针上调用的。

于 2012-08-20T14:39:13.157 回答