简体   繁体   中英

this pointer and member function address

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. :(

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.

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

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

Which prints "008C1186" on my machine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM