This pointer and member function address

I am trying to get the address of a member function, but I do not know how to do this. I would appreciate it if someone 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 cannot understand 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!


Thanks for your reply! However, I still do not work. If I changed 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. :(

0
source share
2 answers

You must prefix the member function with the class name:

&test::g;

- ( ) , .

+1

, :

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

"008C1186" .

+1

Source: https://habr.com/ru/post/1527029/


All Articles