尝试编译此程序时出现三个错误。
我期待以下输出
OFF-ctor
输入 0/1:0 已经 OFF
输入 0/1:1
从 OFF 到 ON ON-ctor dtor-OFF
输入 0/1:1
已经 ON
输入 0/1:0
从 ON 到 OFF OFF-ctor dtor-ON
输入 0/1:1
从关闭到打开 ON-ctor dtor-OFF
输入 0/1:0
从打开到关闭 OFF-ctor dtor-ON
输入 0/1:0
已经关闭 输入 0/1:
以下是程序
#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//Error2->invalid use of non-static member function 'void Machine::off()'
//Error3->invalid use of non-static member function 'void Machine::on()'
};
Machine fsm;
int num;
while (1)
{
cout << "Enter 0/1: ";
cin >> num;
(fsm. *ptrs[num])(); //Error1->expected unqualified-id before '*' token
}
}
代码取自 sourcemaking.com 状态设计模式。我在 eclipse 和 linux g++ 中运行它。请帮忙。