简体   繁体   English

无效使用非静态成员函数c ++

[英]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(); 我试图void on();添加staticvoid 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 在静态成员函数中使用成员Machine :: current无效

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. 函数类型T的左值可以隐式转换为该函数的prvalue指针。 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). 因此,您需要使用& explicit来获取非静态成员函数的地址(即获取非静态成员函数指针)。 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). 如果将它们声明为静态成员函数,则应更改ptrs的类型(到非成员函数指针的数组)。 Note that for static member function it's fine to not use & explicitly. 请注意,对于静态成员函数,可以不使用& explicit。 eg 例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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