2017-06-09 19 views
1

私は私のIndividual.hppファイルに次のコードを持っている:私の.cppファイルに静的メソッドから静的関数ポインタを呼び出す

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

そして、この:

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

私は関数ポインタを使用していますがしかし、私は(this - > * thingyMajigger)(params)と同じ静的呼び出しで私は次のエラーが発生します。

私が言ったコードが、いずれも複数の順列を試してみましたが修飾されていない-ID

が動作するように見えます。誰でも光を分け合えますか?

いいえお返事

+0

非静的メンバー関数へのポインタであるため、 'currentFitnessMethodName'は' Individual'オブジェクトを呼び出す必要があります。あなたの静的関数 'getCurrentFitnessMethodName'では、何の' this'ポインタはありません。そこに使うことができる別の 'Individual'オブジェクトがありますか? – 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 (*staticMethod)(); 

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

からのtypedefを変更するには、それをコンパイルすることができます - 期待通りに出力します:

Ohai, world! 
Hello, world! 
関連する問題