2010-12-28 25 views
2

定数メンバ変数へのポインタの構文が何か不思議でした。constメンバ変数へのポインタ

私はつまり、次の2つの異なる種類があり、非constメンバ関数およびconstメンバ関数へのポインタへのポインタが明示さまざまな種類を知っている:同じ場合、私は思っていた

typedef void (Foo::*Bar)(void); 
typedef void (Foo::*ConstBar)(void) const; 

非constとconstメンバ変数へのポインタ、すなわちの言うことができたとしても、次の二つの異なる種類があり、そうであれば、後者の構文は次のとおりです:

typedef int (Foo::*var); 
typedef int (Foo::*constVar) const; // Not the correct syntax. 

感謝。

答えて

6

ポインタ・ツー・メンバのタイプがメンバの型と一致する必要がある:

typedef  int (Foo::*var); // pointer to a data member of type 'int' 
typedef const int (Foo::*cvar); // pointer to a data member of type 'const int' 

メンバ関数のCONST、資格は、戻り型があるだけのように、その型の一部でありますそのタイプの一部。ただ、それは笑えるようにする

+0

ああ、わかります。私はこの構文をある時点で使用していましたが、私がやっていることはすべてテンプレート化されているので、T(C :: * Get)(void)を取った関数と競合していました。 –

4

typedef const int (Foo::*(Foo::*ConstBar)(void) const); 

ConstBarはのconstメンバ関数は引数を取らないと、int型のconstのメンバーへのポインタを返すへのポインタです。

あなたの質問に構文を覚えている方の一般的なヒント:あなたはそれにあなたが

void name(void) const; // const function 
const int name; // const member 

をクラスのメンバを定義し、その結果、(Foo::*name)によってnameに代わる方法を記述します。

void (Foo::*name)(void) const; // pointer to const function 
const int (Foo::*name); // pointer to const function 
関連する問題