发现在类中定义函数指针变量并赋值会报错,在类外则不会。
在类内部只能先typedef 函数指针类型。
#include <iostream>
#include <stdio.h>
using namespace std;
class Ctest
{
public:
int a = 10;
int* p = &a;
//静态函数
static void statFunc()
{
cout << "This is statFunc" << endl;
}
//void(*pstatFunc)() = &statFunc;在类中这种定义会报错,这种在main函数或者类外部可以用
typedef void(*pstatFunc)();
pstatFunc p0 = &statFunc;
//动态函数
void dynFunc()
{
cout << "This is dynFunc" << endl;
}
typedef void(Ctest::*pdynFunc)();
pstatFunc p1 = &Ctest::dynFunc;
//虚函数
virtual void virtFunc()
{
cout << "This is virtFunc" << endl;
}
typedef void(Ctest::*virFunc)();
pstatFunc p2 = &Ctest::virFunc;
};
int main()
{
Ctest Object;
Ctest* pObject = &Object;
cout << "address of Ctest::statFunc:" << &Ctest::statFunc << endl;
printf( "address of Ctest::dynFunc :%x\n", &Ctest::dynFunc);
printf( "address of Ctest::virtFunc:%x\n", &Ctest::virtFunc);
printf( "address of Ctest::pObject->p:%x\n", pObject->p);
printf( "address of Ctest::Object.p:%x\n", Object.p);
static void (*p_statFunc)();
void (Ctest::*p_dynFunc)();//注意非静态成员函数指针的定义需指明在那个类的域内
void (Ctest::*p_virtFunc)();
p_statFunc = &Ctest::statFunc;
p_dynFunc = &Ctest::dynFunc;
p_virtFunc = &Ctest::virtFunc;
p_statFunc();
//非静态成员函数指针的调用也与普通函数不同,另外因为.*的优先级比()低,所以需要用括号把左边的操作
//数括起来,如果写成Object.*p_dynFunc();将无法通过编译
(Object.*p_dynFunc)();
(Object.*p_virtFunc)();
while(1);
return 1;
}