【发布时间】:2016-12-17 14:23:10
【问题描述】:
我有一个基类Player 和两个派生类Human、Computer。
Player 是一个抽象类,它有一个纯虚方法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;
这行得通。除了我需要指针数组之外,这种情况有什么不同?
(对于问题的长标题表示歉意。如果可以的话,请建议一个新标题)
【问题讨论】:
-
我不完全相信你在这里的设置,你没有发布编译错误,我想(假设内存正确分配给
allPlayers)你应该能够说类似allPlayers[0] = new Human();的话。尽管除非您有信心,否则我会考虑更改设置,以便allPlayers是强指针或类似的向量。
标签: c++ pointers inheritance compiler-errors polymorphism