2011-01-12 55 views
0

我試圖獲取成員函數的地址,但我不知道如何。如果有人能告訴我我做錯了什麼,我將不勝感激。正如你可以在下面我舉的例子看,無論是(長)&摹也不是(長)&這個 - 「G的工作,我不能找出正確的語法:這個指針和成員函數的地址

/* 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)&g); 

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

,它仍然無法正常工作。

PR(&test::g); 

作品在main(),但不

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

???

我想我錯過了一些東西。 :(

+0

地址不一定是數字(這麼長時間可能不夠)。轉換爲(void *)流代碼將只打印地址。 – 2011-01-12 16:38:13

回答

1

必須與類名前綴的成員函數:

&test::g; 

的成員函數(或方法)綁定到類,而不是一個具體實例

1

此外,您還可以使用以下格式直接顯示指針:

的printf( 「%p」,&測試::克);

哪個打印 「008C1186」 我的機器上。