函数名、函数指针、函数名取地址:
函数名:函数首地址,即函数指针常量,
函数调用:
myFunc(11);
(*myFunc)(11);
函数指针:函数指针变量
void(*pFunc1)(int) = myFunc;
typedef void(*FuncPtrType)(int);
FuncPtrType pFunc2 = myFunc;
函数名取地址:函数指针的初始化表达式中的函数名前面的&操作符是可选的,因为函数名被使用时总是由编译器把它转换为函数指针。&操作符只是显式地说明了编译器将隐式执行的任务。
void(*pFunc1)(int) = myFunc;
void(*pFunc2)(int) = &myFunc;
1、普通函数的函数指针
a、返回类型 (*指针变量名)(参数列表)= 函数名;
b、返回类型 (*指针变量名)(参数列表)= &函数名;
c、typedef 返回类型 (*指针类型名)(参数列表);
指针类型名 指针变量名 = 函数名;
指针类型名 指针变量名 = &函数名;
void (*pFunc3)(int) = normalFunc; // 等价于 void (*pFunc3)(int) = &normalFunc;
void(*pFunc4)(int);
pFunc4 = normalFunc;
typedef void (*pFuncType)(int); // pFuncType函数指针类型,不是变量
pFuncType pFunc5 = normalFunc; // 等价于 pFuncType pFunc5 = &normalFunc;
2、类成员函数的函数指针(非静态)
a、返回类型 (类名::*指针变量名)(参数列表) = &类名::函数名;
b、typedef 返回类型 (类名::*指针类型名)(参数列表);
指针类型名 指针变量名 = &类名::函数名;
注:这里的这个&符号是比较重要的,不加&,编译器会认为是在这里调用成员函数,所以需要给出参数列表,否则会报错;加了&,才认为是要获取函数指针。这是C++专门做了区别对待。
调用方法:
(类对象.*指针变量名)(实参列表);
(类指针->*指针变量名)(实参列表);
void (MyClass::*pFunc6)(int) = &MyClass::mClassFunc;
typedef void (MyClass::*classFuncType)(int);
classFuncType pFunc7 = &MyClass::mClassFunc;
MyClass c1;
MyClass *c2 = new MyClass;
(c1.*pFunc6)(1);
(c2->*pFunc6)(1);
3、类成员函数的函数指针(静态)
类的静态成员和普通成员的区别在于,它们是不依赖于具体对象的,所有实例化的对象都共享同一个静态成员,所以静态成员也没有this指针的概念。所以,指向类的静态成员的指针就是普通的指针。
a、返回类型 (*指针变量名)(参数列表) = 类名::函数名;
b、返回类型 (*指针变量名)(参数列表) = &类名::函数名;
调用方法跟普通函数一样:指针变量名(实参列表)
void (*pFunc8)(int) = MyClass::mClassStaticFunc;
void (*pFunc9)(int) = &MyClass::mClassStaticFunc;
c、typedef 返回类型 (*指针类型名)(参数列表);
指针类型名 指针变量名 = 类名::函数名;
指针类型名 指针变量名 = &类名::函数名;
typedef void(*classStaticFuncType)(int);
classStaticFuncType pFunc10 = MyClass::mClassStaticFunc;
classStaticFuncType pFunc11 = &MyClass::mClassStaticFunc;
4、模板函数的函数指针
a、返回类型 (*指针变量名)(参数列表) = 模板函数名<参数类型>;
b、返回类型 (*指针变量名)(参数列表) = &模板函数名<参数类型>;
void (*pFunc12)(int) = templateFunc;
void (*pFunc13)(int) = &templateFunc;
c、typedef 返回类型 (*指针类型名)(参数列表);
指针类型名 指针变量名 = 模板函数名<参数类型>;
指针类型名 指针变量名 = &模板函数名<参数类型>;
typedef void(*templateFuncType)(int);
templateFuncType pFunc14 = templateFunc;
templateFuncType pFunc15 = &templateFunc;