C++ mutual class dependency(C++ 相互类依赖)
问题描述
I am writing a card game in C++. I have a player class, which handles the actions (i.e. selecting a card to lay). If the player is a human, it will use a GUI class, if it is a computer, it will use an AI class.
In order for the AI class to make decisions, it needs to know some things about every player that change during the game, for example the number of cards on hand. Right now I store a player pointer for every player in a vector in the AI class.
However, this leads to my problem, the AI class needs to #include the Player class, and the player class needs to #include the AI class.
Maybe the solution isn't how to handle the #includes, but rather a better way to structure the classes?
I guess both Player and AI class have common methods for that card game (get card, put card, shuffle, bet, all in...) which can be inherited from a base class CardPlayer or composed during runtime using interfaces (see Strategy Pattern).
To interface the Human Player class to the GUI, create a suitable interface, for example:
typedef struct PlayerInfoStruct {
---player info variables here---
};
class IGUIPlayer {
virtual PlayerInfoStruct GetPlayerInfo(...) = 0;
---other methods exclusive to the GUI-player interaction here---
};
and implement that interface in your HumanPlayer inheriting it:
class HumanPlayer : public CardPlayer, public IGUIPlayer {
PlayerInfoStruct GetPlayerInfo() {---method---}
---other methods here---
}
and in your GUI you point to each human player using its interface:
---somewhere in your GUI Class---
IGUIPlayer* humanplayer1 = <pointer to HumanPlayer>;
With that, GUI Class depends on IGUIPlayer. HumanPlayer depends on both IGUIPlayer and CardPlayer. AIPlayer depends only on CardPlayer. No circular stuff!
Using an interface means that you could, at any moment, provide AI players' info in the GUI, by simply inheriting IGUIPlayer to AIPlayer and implementing the pure virtual methods, without modifying the GUI a single bit. It took me a bit to get used to this (and I still keep on learning), but I can't resist to its inmense power.
这篇关于C++ 相互类依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 相互类依赖
基础教程推荐
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01