使用基类指针数组调用派生类方法,该指针具有指向派生类对象的指针

时间:2016-12-17 14:23:10

标签: c++ pointers inheritance compiler-errors polymorphism

我有一个基类Player和两个派生类HumanComputerPlayer是一个抽象类,它具有纯虚方法PlayMove

现在,在Game课程中,我希望有一个在游戏中玩的所有玩家阵列。很少有玩家属于Human&其他人将是Computer。我希望以这样的方式实现它 - 对于数组中的每个玩家,我将调用PlayMove并根据它的播放器类型,调用它自己的PlayMove

例如,说 array = {humanPlayer, computerPlayer} array[0].PlayMove()应登陆Human::PlayMove() array[1].PlayMove()应登陆Computer::PlayMove()

-

我做了什么 -

class Game
{
    Human &h;
    Computer &c;
    Player **allPlayers;
}

Game::Game()
{
    h = new Human();
    c = new Computer();
    // problem is occuriung in following three line
    allPlayers = new (Player*)[2];
    allPlayers[0] = h;
    allPlayers[1] = c;
}

我知道

Base *b;
Derived d;
b = &d;
这是有效的。除了我需要指针数组之外,这种情况有何不同?

(对问题的长标题表示道歉。如果可以的话,请提出新标题)

1 个答案:

答案 0 :(得分:0)

我在代码中看到了几个错误。我在下面的代码中纠正了这个错误,

class Player
{};
class Human : public Player
{};
class Computer : public Player
{};

class Game
{
public:
    Game();
    Human *h;
    Computer *c;
    Player **allPlayers;
};

Game::Game()
{
    h = new Human();
    c = new Computer();
    // Following three lines are just fine
    allPlayers = new Player*[2];
    allPlayers[0] = h;
    allPlayers[1] = c;
}

参考必须在施工初始化清单中初始化。也不允许引用临时对象,所以

"Game::Game():h(new Human),c(new Computer)"

是不允许的。解决方案是使用指针h和c而不是引用。