2016-12-26 367 views
2

我正在关注这个example。但是,当我编译,它会返回一个错误:非静态成员函数的使用无效C++

Invalid use of non-static member function

在该行

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

我试图在类

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 
}; 

添加staticvoid on();但抱怨

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

你能帮我解决这个问题吗?

回答

5

与静态成员函数或自由函数不同,非静态成员函数不会向成员函数指针implicitly convert

(重点煤矿)

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.

所以你需要使用&明确采取的非静态成员函数的地址(即获得非静态成员函数指针)。例如

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

如果声明为静态成员函数,应更改的ptrs类型(非成员函数指针阵列)。请注意,对于静态成员函数,可以明确不使用&。例如

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

啊,oui。它的工作原理,但你能解释为什么吗?谢谢 – GAVD

+0

@GAVD解释添加。 – songyuanyao

+0

@songyuanyao pcap库下的pcap_loop()会抛出类似的错误。请你看看这个,让我知道你有什么想法吗? Tqvm 0​​http://stackoverflow.com/questions/43108998/c-pcap-loop-arguments-issue – Wei

相关问题