我已经完成了一项家庭作业,我似乎无法理解。我们的老师希望我们编写一个有限状态机。这是代码
#ifndefine
#define FINITE_STATE_MACHINE_H
#include <iosfwd>
class FiniteStateMachine
{
Private:
friend std::ostream &operator<< (std::ostream &, FiniteStateMachine const &);
public:
FiniteStateMachine(){}
virtual FiniteStateMachine *changeState() const = 0;
virtual char const *toString() const = 0;
virtual ~FiniteStateMachine(){}
};
class ON : public FiniteStateMachine
{
private:
public:
ON(){}
FiniteStateMachine *changeState() const;
char const *toString() const;
};
class OFF : public FiniteStateMachine
{
private:
public:
OFF(){ }
FiniteStateMachine *changeState() const;
char const *toString() const;
};
#endif
指令是创建一个FiniteStateMachine.cpp文件,其中包含所有相关的成员函数,使OFF状态转换为ON状态,反之亦然。
我试图写一个changeState()函数来返回一个相反状态的新实例,但它似乎不想工作,我不确定我要去哪里错。
我试图在FiniteStateMachine.cpp中使用以下内容实例化并返回一个新的ON对象
FiniteStateMachine *OFF::changeState() const
{
FiniteStateMachine *on = new ON;
return *on;
}
并且编译器返回以下错误 无法转换'FiniteStateMachine&#39; to&#39; FiniteStateMachine *&#39;作为回报
一位同学建议将其放入构造函数中,而不是简单地调用changeState()
OFF::OFF()
{
FiniteStateMachine *OFF::changeState() const
{
FiniteStateMachine *on = new ON;
return *on;
}
}
编译器返回错误 声明中的qualified-id&#39;(&#39;令牌
表示它在changeState和()&#39;之间 在更多的键盘敲击之后,似乎我需要写
FiniteStateMachine *OFF::changeState() const
{
return new OFF();
}