先看代码
#include <iostream>
using namespace std;
typedef void (*func)(); //含简单的定义一个函数指针,很容易用这个方法来实现指令,用作各种handler等等
void print()
{
cout << "print" <<endl;
}
class A
{
typedef void (A::*classfunp)();//指明这个函数指针是指向类A的,不能指向其他类的函数
public:
classfunp g;
void print()
{
cout << "A::print" << endl;
}
void h()
{
g = &A::print; // 将函数print在A中的地址赋给函数指针g。使用&this->print报错为forbids taking the address of a bound memeber function to from a pointer to memeber function,意思就是不能将一个成员函数的地址当成一个指向成员函数的指针,下面解释,为什么
(this->*g)(); //去掉this不对,因为g并不是A的一个成员变量,报错为:must use .* or->* to call point-to-member function
}
};
int main()
{
A a;
a.h();
returnr 0;
}
----->A::print;
要知道为什么不能用this->print,请看
4.2Array-to-pointer conversion [conv.array]
1An lvalue or rvalue of type “array ofN T” or “array of unknownbound of T” can be converted to an rvalue
oftype “pointer to T.” The result is a pointer to the first elementof the array.
2 A string literal(2.13.4) that is not a wide string literal can be converted to anrvalue of type “pointer to
char”; awide string literal can be converted to an rvalue of type “pointerto wchar_t”. In either case,
theresult is a pointer to the first element of the array. Thisconversion is considered only when there is an
explicitappropriate pointer target type, and not when there is a general needto convert from an lvalue to an
rvalue.[Note: this conversion is deprecated. See Annex D. ] For the purposeof ranking in overload resolution
(13.3.3.1.1),this conversion is considered an array-to-pointer conversion followedby a qualification
conversion (4.4).[Example: "abc" is converted to “pointer to const char”as an array-to-pointer conversion,
andthen to “pointer to char” as a qualification conversion. ]
4.3Function-to-pointer conversion [conv.func]
1An lvalue of function type T can be converted to an rvalue of type“pointer to T.” The result is a pointer to
thefunction.50)
2 [Note: See 13.4 foradditional rules for the case where the function is overloaded.]
从上面我们知道为什么不能直接使用一个对象的函数地址了,因为重载,例如
一个类里面有函数f(),f(int),当我们使用this->f时,到底使用的是要哪个f的地址呢,除非我们传入参数进去
通过下面的例子就知道了typedef void (*func)(); void f(); void f(int); func p = f; p(); p(1);//错误,因为函数指针p是指向f()的而不是f(1)
通过使用函数指针,我们可以制作各种handler,用这些handler为我们做不同的事,如信号的一个函数
signal(intsigno, int (*handler)());
在游戏里面编写各种gm指令;做一些框架,为通用功能的特殊部分编写自己的接口,通过函数指着指向他们等等