这个指针和成员函数地址

时间:2011-01-12 13:13:51

标签: c++ function member memory-address

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

???

我想我错过了什么。 :(

2 个答案:

答案 0 :(得分:1)

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

&test::g;

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

答案 1 :(得分:1)

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

printf(“%p”,&amp; test :: g);

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