【发布时间】:2013-12-13 16:32:25
【问题描述】:
我正在开发一个面向对象的井字游戏,但遇到了问题。我的一个类充当游戏的主控制器并控制所有其他对象。下面是该类的精简版。
最终用户可以选择一到两个玩家。因此,我没有必要同时创建第二个玩家和一个 AI 玩家。游戏只需要其中一个。正如您在下面看到的,我尝试使用 if 语句来解决问题,但对象没有范围。
如何根据传递给 Game 构造函数的玩家数量来初始化一个对象或另一个对象?
谢谢!
游戏.h
#include "Player.h"
#include "AIPlayer.h"
class Game
{
private:
Player human;
// I would like to put these here so they have scope
// but it is unecessary to declare them both
// If the user chooses one player then human2 is unecessary
// if the user choosed two player then ai is unecessary
AIPlayer ai;
Player human2;
public:
Game(int players)
{
if (players == 1)
{
AIPlayer ai; // this does not have scope
}
else
{
Player human2; // this does not have scope
}
}
};
【问题讨论】: