我正在开展一个项目,其中有两个玩家对象和一个游戏对象。
两个玩家对象需要访问游戏对象的功能 display(),但我不知道如何做到这一点。
以下是突出核心问题的片段:
class Game
{
public:
Game() {}
display() {...}
...
};
class Player
{
public:
Player() {}
void input()
{
...
// display();
...
}
};
请建议一种解决此问题的方法。如果你发现这个设计模式存在根本问题,请随意纠正!
答案 0 :(得分:1)
为什么不呢?
void input()
{
game.Display();
}
但可能需要将Player
对象传递给它。因此,改变方式:
class Player; // FORWARD declaration
class Game
{
public:
Game() {}
void display(Player& player); // Implement elsewhere not here.
// Another way
void display(Player* player = NULL); // Implement elsewhere not here.
...
};
...
void input()
{
game.Display(*this);
game.Display(this); // another way
}