this pointer and member function address

2019-01-29 10:32发布

问题:

I'm trying to get the address of a member function, but I don't know how. I would appreciate if somebody could tell me what I'm doing wrong. As you can see in my example below, neither (long)&g nor (long)&this->g work and I can't figure out the correct syntax:

/* 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();
}

Thanks in advance!


Thank you for your reply! However I still don't get it to work. If I change the line

PR( (long)&g );

to

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

, it still doesn't work.

PR( &test::g );

works in main(), but not

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

???

I think I'm missing something. :(

回答1:

You must prefix the member function with the class name :

&test::g;

A member function (or method) is bound to a class, not a specific instantiation.



回答2:

Also, you can use the following format to show pointers directly:

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

Which prints "008C1186" on my machine.