c++ - 状态设计模式-编译错误

标签 c++ design-patterns compiler-errors


我在尝试编译这个程序时遇到三个错误。

我期待以下输出

OFF-ctor
Enter 0/1: 0 already OFF
Enter 0/1: 1
going from OFF to ON ON-ctor dtor-OFF
Enter 0/1: 1
already ON
Enter 0/1: 0
going from ON to OFF OFF-ctor dtor-ON
Enter 0/1: 1
going from OFF to ON ON-ctor dtor-OFF
Enter 0/1: 0
going from ON to OFF OFF-ctor dtor-ON
Enter 0/1: 0
already OFF Enter 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++ 中运行它。 请帮忙。

最佳答案

要获取指向成员函数的指针,您需要使用 &(即使获取指向非成员函数的指针是可选的):&Machine::off, &Machine::on

对于另一个,您需要意识到 .* 是单个标记,因此您需要删除两个字符之间的空格:(fsm.*ptrs[num]) ();

关于c++ - 状态设计模式-编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15082894/

相关文章:

c++ - 类方法类型的 decltype

c# - 使用事件而不是异常来实现错误处理

在同一个类中使用多种类型的数据库时的 PHP 依赖注入(inject)

ios - iOS : Use of undeclared identifier error in simple calculator [closed]

c++ - 如何在C++文件中声明标识符JSON?

c++ - OpenMP:局部变量是否自动私有(private)?

c++ streaming io/Design a stringstream+custom streambuf 或在 char 数组上使用 mem 工具?

c++ - 为什么要创建 GObject 系统?

java - 一长串 if/else/execute 代码分支的最佳设计模式/方法

C++:错误:无效使用限定名