0

我正在尝试获取成员函数的地址,但我不知道如何。如果有人能告诉我我做错了什么,我将不胜感激。正如您在下面的示例中看到的那样, (long)&g 和 (long)&this->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 );

???

我想我错过了一些东西。:(

4

2 回答 2

1

您必须在成员函数前面加上类名:

&test::g;

成员函数(或方法)绑定到类,而不是特定的实例化。

于 2011-01-12T13:24:13.800 回答
1

此外,您可以使用以下格式直接显示指针:

printf("%p", &test::g);

在我的机器上打印“008C1186”。

于 2011-01-12T13:32:42.677 回答