【发布时间】:2012-11-28 08:36:34
【问题描述】:
这是状态机设计模式的一个例子。我遇到了一些问题,请解释并给出解决方案。
这是代码:
#include <iostream>
using namespace std;
class Machine
{
class State *current;
public:
Machine();
void setCurrent(State *s)
{
current = s;
}
void on();
void off();
};
class State
{
public:
virtual void on(Machine *m)
{
cout << " already ON\n";
}
virtual void off(Machine *m)
{
cout << " already OFF\n";
}
};
void Machine::on()
{
current->on(this);
}
void Machine::off()
{
current->off(this);
}
class ON: public State
{
public:
ON()
{
cout << " ON-ctor ";
};
~ON()
{
cout << " dtor-ON\n";
};
void off(Machine *m);
};
class OFF: public State
{
public:
OFF()
{
cout << " OFF-ctor ";
};
~OFF()
{
cout << " dtor-OFF\n";
};
void on(Machine *m)
{
cout << " going from OFF to ON";
m->setCurrent(new ON());
delete this;
}
};
void ON::off(Machine *m)
{
cout << " going from ON to OFF";
m->setCurrent(new OFF());
delete this;
}
Machine::Machine()
{
current = new OFF();
cout << '\n';
}
int main()
{
void(Machine:: *ptrs[])() =
{
Machine::off, Machine::on
};
Machine fsm;
int num;
while (1)
{
cout << "Enter 0/1: ";
cin >> num;
(fsm. *ptrs[num])();
}
}
这是错误:
prog.cpp:在函数“int main()”中:
prog.cpp:89:错误:非静态成员函数“void Machine::off()”的使用无效
prog.cpp:89:错误:非静态成员函数“void Machine::on()”的使用无效
prog.cpp:97:错误:“*”标记之前的预期 unqualified-id
【问题讨论】:
-
这里有很多奇怪的东西,我不知道从哪里开始。一方面,听听你的编译器......你正在尝试使用 off 和 on 方法,就像它们是静态的一样。您需要一个 Machine 对象的实例才能使用它们。
-
@ScoPi 他有一个:
fsm。它的初始化列表和调用程序被破坏了(后者字面意思是一个空格)。 -
我的建议就是不要写像这样的 C++。
标签: c++