How can I call class member function by a globle function pointer?

Z

zx.zhangxiong

Dear all,


I'm puzzled about the usage of class member function. Any help would be

appreciated.


class Account {
...
public:
void test(int i) {};
...



};


// error: must use .* or ->* to call pointer-to-member function
void (*funcPtr)(int i) = &Account::test;

How can I call class member function by a globle function pointer?
 
K

Karl Heinz Buchegger

Dear all,

I'm puzzled about the usage of class member function. Any help would be

appreciated.

class Account {
...
public:
void test(int i) {};
...

};

// error: must use .* or ->* to call pointer-to-member function
void (*funcPtr)(int i) = &Account::test;

How can I call class member function by a globle function pointer?

You need an object for which you want to call a member function!
eg.

#include <iostream>

class Account {
public:
void test(int i) { std::cout << i << std::endl; }
};

void (Account::*funcPtr)(int i) = &Account::test;
Account* pTheAccount;

void foo()
{
Account Test;
(Test.*funcPtr)( 7 );
(pTheAccount->*funcPtr)( 5 );
}

int main()
{
Account MyAccount;
pTheAccount = &MyAccount;

foo();
}
 
Z

zx.zhangxiong

Thanks
But is there any way to call a member function by a outer-class
function pointer?
 
J

Jonathan Mcdougall

But is there any way to call a member function by a outer-class
function pointer?

No. The type of f() in

class C
{
void f();
};

is not void(), but void C::(). Hence, to get a pointer to it, you must
do

void (C::*p)();

Now if you want to use a pointer to a free function with a class
member, you must make it static. For example :

class C
{
public:
static void start();
};

void f()
{
void (C::*p1)() = &C::start; // error
void (*p2)() = &C::start; // ok
}

You'll have to do that often if you want to use classes and C functions
together. For example, many win32 functions expect a pointer to a free
function, not to a class member and you'll have to use a static member.

Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top