2011-01-12 17 views
0

私はメンバ関数のアドレスを取得しようとしていますが、どのようにわかりません。誰かが私が間違っていることを私に教えてもらえれば幸いです。あなたは以下の私の例でわかるように、どちらも(長い)&グラムも(長い)& this->グラム仕事と私は正しい構文を把握することはできません。事前にこのポインタとメンバ関数のアドレス

/* Create a class that (redundantly) performs data member selection 
and a member function call using the this keyword (which refers to the 
address of the current object). */ 

#include<iostream> 
using namespace std; 

#define PR(STR) cout << #STR ": " << STR << endl; 

class test 
{ 
public: 
    int a, b; 
    int c[10]; 
    void g(); 
}; 

void f() 
{ 
    cout << "calling f()" << endl; 
} 

void test::g() 
{ 
    this->a = 5; 
    PR((long)&a); 
    PR((long)&b); 
    PR((long)&this->b);  // this-> is redundant 
    PR((long)&this->c);  // = c[0] 
    PR((long)&this->c[1]); 
    PR((long)&f); 
// PR((long)&g);  // this doesn't work 
// PR((long)&this->g);  // neither does this 

    cout << endl; 
} 

int main() 
{ 
    test t; 
    t.g(); 
} 

感謝を!


ありがとうございました!しかし、私はまだそれを動作させることはありません。私は

PR((long)&test::g); 

PR((long)&g); 

行を変更した場合、それはまだ動作しません。

PR(&test::g); 

()メインでの作品ではなく

PR((long)&test::g); 

???

私は何かが不足していると思う。 :(

+0

アドレスは必ずしも数字ではありません(長すぎてはなりません)。 (void *)にキャストすると、ストリームコードはアドレスを出力します。 –

答えて

1

あなたは、クラス名とメンバ関数の前に付ける必要があります。

&test::g; 

メンバ関数(またはメソッド)をクラスではなく、特定のインスタンスにバインドされている。また

1

を、することができます直接ポインタを表示するには、次の形式を使用します。

のprintf( "%pを"、&テスト::グラム);

私のマシン上で "008C1186" を出力します。

関連する問題