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
  };
  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()”<br> prog.cpp:89:错误:无效使用非静态成员函数 'void Machine::on()'<br> prog.cpp:97: 错误:在 '*' 标记之前预期 unqualified-id

4

1 回答 1

6

有两个错误:

一,地址操作符对于创建指向成员的指针是强制性的。所以他们的数组初始化应该是:

void(Machine:: *ptrs[])() = 
{
  &Machine::off, &Machine::on
};

二,取消引用指向成员的指针的运算符是.*. 这是一个单一的标记,所以不允许有空格:

(fsm.*ptrs[num])();
于 2012-11-28T08:45:04.923 回答