我正在尝试基于口香糖球机对状态机进行编码。我有一个基本状态的接口类,而我有使用此接口的特定状态。我有四种状态,no_quarter
,has_quarter
,sold
和sold_out
状态。我还有一个gumball机器类来处理这些状态,根据我的机器所处的状态,它将进入该类并执行所需的操作。这是我的代码有问题,我也会发布我的功能。
Gumball_Machine.h
class Gumball_Machine
{
private:
int gumball_count;
State *current_state;
No_Quarter_State *nqs;
Has_Quarter_State *hqs;
Sold_State *ss;
Sold_Out_State *sos;
public:
Gumball_Machine(int inventory)
{
gumball_count = inventory;
nqs = new No_Quarter_State(this);
hqs = new Has_Quarter_State(this);
ss = new Sold_State(this);
sos = new Sold_Out_State(this);
if (gumball_count == 0)
set_state(sos);
else
set_state(nqs);
}
void insert_quarter()
{
current_state->insert_quarter();
}
void eject_quarter()
{
current_state->eject_quarter();
}
void turn_crank()
{
current_state->turn_crank();
}
void dispense()
{
current_state->dispense();
}
void set_state(State *new_state)
{
current_state = new_state;
}
State *get_no_quarter_state()
{
return nqs;
}
State *get_has_quarter_state()
{
return hqs;
}
State *get_sold_state()
{
return ss;
}
State *get_sold_out_state()
{
return sos;
}
No_Quarter_State.h
#ifndef NO_QUARTER_STATE_H_INCLUDED
#define NO_QUARTER_STATE_H_INCLUDED
#include "State.h"
class No_Quarter_State: public State
{
public:
No_Quarter_State(Gumball_Machine *gbm);
void insert_quarter();
void eject_quarter();
void turn_crank();
void dispense();
};
#endif // NO_QUARTER_STATE_H_INCLUDED
No_Quarter_State.cpp
#include "No_Quarter_State.h"
#include "Gumball_Machine.h"
No_Quarter_State::No_Quarter_State(Gumball_Machine *machine)
{
machine = machine;
}
void No_Quarter_State::insert_quarter()
{
cout << "You inserted a quarter.\n";
machine->set_state(machine->get_has_quarter_state());
}
void No_Quarter_State::eject_quarter()
{
cout << "You must insert a quarter before you can eject one.\n";
}
void No_Quarter_State::turn_crank()
{
cout << "You must insert a quarter before you can crank the handle.\n";
}
void No_Quarter_State::dispense()
{
cout << "You need to pay first before you can get a gumball.\n";
}
我遇到问题的一行是No_Quarter_State.cpp
machine->set_state(machine->get_has_quarter_state());
这给了我一个运行时错误。我见过这样的例子,但我不完全确定这在C ++中是否合法。我正在尝试切换我的口香糖机器对象的状态。
我得到的错误是通用无响应错误:"test.ext has stopped working"
。我正在使用CodeBlocks来编写代码。
答案 0 :(得分:6)
在构造函数中,假定的成员变量machine
被参数隐藏。
No_Quarter_State::No_Quarter_State(Gumball_Machine *machine)
{
machine = machine;
}
您可以使用initializer list syntax来解决此问题:感谢Sneftel和NathanOliver
No_Quarter_State::No_Quarter_State(Gumball_Machine *machine)
: machine(machine)
{
}
但是,在常规方法函数中,如果将方法参数命名为与成员变量相同,则必须使用this->
。用于避免该问题的典型样式是添加m_
或将_
附加到成员名称。