开发者

C++ State machine affecting "HAS-A Parent"

开发者 https://www.devze.com 2023-01-05 02:22 出处:网络
I\'m trying to implement a State Machine. The State Machine will have to have an impact on the obj开发者_开发百科ect that \"HAS\" it as a member.

I'm trying to implement a State Machine. The State Machine will have to have an impact on the obj开发者_开发百科ect that "HAS" it as a member.

However, I obviously can't include the "StateMachine" in the "Game" class AND include the "Game" header in the "StateMachine" class.

How do I get around this problem?


As your client class is a member rather than an inheriting daughter, you can not access any private state of the parent (which I'm sure you knew), so you have a limited number of choices:

  • Expose some state in the parent publicly and diddle that (but this is poor design and should be avoided)
  • Give the parent a public notification interface of some kind and use that (better then the above, but still not great)
  • Pass a call-back to the client (a very c programmer type of solution)
  • Use some kind of signal/slots mechanism to notify the parent that something interesting has happened. If you're using any of the big frameworks (Qt, etc...), this may already be available


Use forward class declarations.


Forward declare the classes; as an example:

class StateMachine;

class Game
{
    StateMachine *sm;
    // stuff
};


To clarify a bit.

If your header file only has pointers of a type defined somewhere else, you don't need to include that header file in your header file.

instead, do a forward declaration such as class StateMachine; then include the StateMachine header file in your CPP file, after the include to your own header file.

0

精彩评论

暂无评论...
验证码 换一张
取 消