简体   繁体   中英

Invalid use of non-static member function c++

I am following this example . But when I compile, it returns an error:

Invalid use of non-static member function

at the line

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

I tried to add static to void on(); at class

class Machine
{
  class State *current;
  public:
    Machine();
    void setCurrent(State *s)
    {
        current = s;
    }
    static void on(); // I add static here ...
    static void off(); // and here
};

But it complains that

Invalid use of member Machine::current in static member function

Can you help me fix this?

Unlike static member functions or free functions, non-static member functions won't implicitly convert to member function pointers.

(emphasis mine)

An lvalue of function type T can be implicitly converted to a prvalue pointer to that function. This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist.

So you need to use & explicitly to take the address of the non-static member functions (ie to get non-static member function pointers). eg

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

If you declare them as static member function, you should change the type of ptrs (to array of non-member function pointers). Note that for static member function it's fine to not use & explicitly. eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM