2017-06-09 279 views
1

靜態函數指針我在Individual.hpp文件下面的代碼:調用從靜態方法

typedef string (Individual::*getMethodName)(void);  
static getMethodName currentFitnessMethodName; 
static string getCurrentFitnessMethodName(); 

這對我的.cpp文件:

string Individual::getCurrentFitnessMethodName(){ 
    return (Individual::*currentFitnessMethodName)(); 
} 

我使用的函數指針在我的代碼的其他部分,但總是在同一個對象上下文中,所以我確實(this - > * thingyMajigger)(params),但通過該靜態調用,我得到以下錯誤:

Expected unqualified-id

我已經嘗試了所述代碼的多個排列,但似乎沒有任何工作。任何人都可以分享一些光?

乾杯

+0

作爲非靜態成員函數的指針,'currentFitnessMethodName'需要調用'Individual'對象。在你的靜態函數'getCurrentFitnessMethodName'中,沒有'this'指針。你有另外一個可以在那裏使用的「個人」對象嗎? – aschepler

+0

爲什麼使用靜態和函數指針而不是使用object.method正確執行它? – stark

+0

@aschepler,不,我不知道。我只是把它作爲一個例子來描述。 –

回答

1

你的typedef是什麼讓你搞砸了。靜態方法只是正常的函數,它們恰好可以訪問其類的受保護/私有靜態成員。

更改的typedef簡單:

typedef string (*getMethodName)(void); 

前者語法對於非靜態成員方法。


作爲一個例子,下面不編譯:

#include <iostream> 
#include <string> 

using namespace std; 
class Foo { 
public: 
    typedef string (Foo::*staticMethod)(); 

    static staticMethod current; 

    static string ohaiWorld() { 
     return "Ohai, world!"; 
    } 

    static string helloWorld() { 
     return "Hello, world!"; 
    } 

    static string callCurrent() { 
     return Foo::current(); 
    } 
}; 

Foo::staticMethod Foo::current = &Foo::ohaiWorld; 

int main() { 
    cout << Foo::callCurrent() << endl; 
    Foo::current = &Foo::helloWorld; 
    cout << Foo::callCurrent() << endl; 
    return 0; 
} 

但改變從

typedef string (Foo::*staticMethod)(); 

的的typedef

typedef string (*staticMethod)(); 

允許它來編譯 - 並如預期的那樣輸出:

Ohai, world! 
Hello, world!