I need some help with inheritance and coding to interfaces in C++. I'm creating a state machine from which I'll derive another state machine. Therefore I have two interacting parts, a StateMachine
and a State
. The problem is that with this design, I cannot derive a specialised State
from either the StateMachine
or a DerivedStateMachine
.
class StateMachine; //fwd class State { public: virtual void action(StateMachine *engine) = 0; virtual ~State() = default; }; class StateMachine { public: StateMachine() = default; explicit StateMachine(State &state) : state_(&state) {}; virtual void setState(State &state) { state_ = &state; } [[nodiscard]] virtual State *getState() const { return state_; } protected: State *state_ = nullptr; };
class DerivedStateMachine : public StateMachine { public: using StateMachine::StateMachine; int doSpecializedThings(){ return special_thing_; } void setSpecialState(int specialState) { special_thing_ = specialState; } private: int special_thing_; };
The issue with DerivedStateDependsOnGeneralStateMachine
is that a StateMachine*
doesn't have access to the doSpecializedThings()
method.
class DerivedStateDependsOnGeneralStateMachine : public State { virtual void action(StateMachine *engine) { int important_value = engine->doSpecializedThings(); }; };
And the problem with DerivedStateDependsOnDerivedStateMachine
is that you can't override a method with different arguments to the parent.
class DerivedStateDependsOnDerivedStateMachine : public State { void action(DerivedStateMachine *engine) override { engine->doSpecializedThings(); }; };
Can anybody see a way out of this knot I've tied myself in? Clearly I've messed up the design somewhere. What's 'normal' (for want of a better word) in such situations?
https://stackoverflow.com/questions/65744921/designing-and-implementing-an-interface-in-c-im-damned-if-i-do-and-im-damne January 16, 2021 at 07:39AM
没有评论:
发表评论