我正在开发一个面向对象的tic tac toe游戏,我遇到了问题.我的一个类充当游戏的主控制器并控制所有其他对象.下面是该类的剥离版本.
最终用户可以选择一到两个玩家.因此,我没有必要创建第二个玩家和一个ai玩家.游戏只需要一个或另一个.正如您在下面看到的,我尝试使用if语句来解决问题,但是对象没有范围.
如何根据传递给Game构造函数的玩家数量初始化一个或另一个对象?
谢谢!
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
}
}
};
Run Code Online (Sandbox Code Playgroud)
我的建议是从公共基类(例如,Player)派生AIPlayer和Player(或者更好的HumanPlayer),并在Game中有一个指向该基类的指针.然后构造函数实例化AIPlayer或HumanPlayer并将其分配给指针.
AIPlayer和HumanPlayer之间不同的任何方法都应该在基类Player中声明为虚方法,然后在派生类中实现.
| 归档时间: |
|
| 查看次数: |
237 次 |
| 最近记录: |