2016-12-26 563 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

相關問題