可以通过成员函数指针来调用, 先来介绍一下成员函数指针,其与函数指针基本一致,只是要添加作用域运算符。
class Test
{
public:
Test(int iNum, char ch) : m_iNum(iNum), m_cCh(ch) { }
void say_hello()
{
cout << "Hello" << endl;
}
void in_test(int iNum)
{
cout << iNum << endl;
}
private:
int m_iNum;
char m_cCh;
};
// 使用using语法来给成员函数指针取别名
using say_hello = void (Test::*)();
// 用typedef实现, 与上面等价
typedef void (Test::*another_say_hello)();
int main()
{
Test t(5, 'a');
// 获取成员函数指针
say_hello pfn = &Test::say_hello;
// 通过成员函数指针调用对应成员函数
(t.*pfn)();
Test *pt = &t;
// 通过成员函数指针调用对应成员函数
(pt->*pfn)();
return(0);
}
上面是使用了C++的关于成员函数的语法来调用了成员函数, 接下来直接使用函数指针来调用:
class Test
{
public:
Test(int iNum, char ch) : m_iNum(iNum), m_cCh(ch) { }
void say_hello()
{
cout << "Hello" << endl;
}
void in_test(int iNum)
{
cout << iNum << endl;
}
private:
int m_iNum;
char m_cCh;
};
using in_test = void (__thiscall *)(Test */* 这个就是this指针 */, int);
int main()
{
Test t(5, 'a');
in_test pfn_in_test = nullptr;
// 获取原本成员函数地址
auto mem_in_test = &Test::in_test;
// 用函数指针指向它
pfn_in_test = (in_test)*(int *)&mem_in_test;
// 调用成员函数
pfn_in_test(&t, 5);
return(0);
}
(完)