【C/C++】类成员函数地址的获取及使用方法

#include <iostream>

using namespace std;

class A
{
public:

A() : a(910){};

void foo1(int i) { cout << "hello, foo1" << endl;}

void foo2(int i) { cout << "hello, foo2\t" << a << endl;}

private:

int a;

};

template <class FromType, class ToType>
void TypeCast(FromType f, ToType& t)
{
union {FromType ft; ToType tt;} ut;
ut.ft = f;
t = ut.tt;

}

void bar(int i)
{

}

int main()
{

A an;

void (A::*pFunc1)(int) = &A::foo1;

cout << pFunc1 << endl;

//cout << (long)(pFunc1) << endl;

//cout << (long)(void*)(pFunc1) << endl;

void (A::*pFunc2)(int) = &A::foo2;

cout << pFunc2 << endl;

//cout << (long)(pFunc2) << endl;

long addr1, addr2;

TypeCast<void (A::*)(int), long>(&A::foo1, addr1);

cout << addr1 << endl;

TypeCast<void (A::*)(int), long>(&A::foo2, addr2);

cout << addr2 << endl;

(*(void(*)(int))(addr1))(20); //all right, it doesn't call any member of (A*)NULL

(*(void(*)(A*,int))(addr1))(&an, 20);

//(*(void(*)(int))(addr2))(18); //==>lead to segment fault, for it calls ((A*)NULL)->a;

(*(void(*)(A*,int))(addr2))(&an, 18);

void (*pFunc3)(int) = bar;

cout << (long)pFunc3 << endl;

} 


你可能感兴趣的:(【C/C++】类成员函数地址的获取及使用方法)