轉(zhuǎn)載請(qǐng)注明原文網(wǎng)址:
http://www.cnblogs.com/xianyunhe/archive/2011/11/26/2264709.html
函數(shù)指針是通過指向函數(shù)的指針間接調(diào)用函數(shù)。函數(shù)指針可以實(shí)現(xiàn)對(duì)參數(shù)類型、參數(shù)順序、返回值都相同的函數(shù)進(jìn)行封裝,是多態(tài)的一種實(shí)現(xiàn)方式。由于類的非靜態(tài)成員函數(shù)中有一個(gè)隱形的this指針,因此,類的成員函數(shù)的指針和一般函數(shù)的指針的表現(xiàn)形式不一樣。
1、指向一般函數(shù)的指針
函數(shù)指針的聲明中就包括了函數(shù)的參數(shù)類型、順序和返回值,只能把相匹配的函數(shù)地址賦值給函數(shù)指針。為了封裝同類型的函數(shù),可以把函數(shù)指針作為通用接口函數(shù)的參數(shù),并通過函數(shù)指針來間接調(diào)用所封裝的函數(shù)。
下面是一個(gè)指向函數(shù)的指針使用的例子。
#include <iostream.h>
/*指向函數(shù)的指針*/
typedef int (*pFun)(int, int);
int Max(int a, int b)
{
return a > b ? a : b;
}
int Min(int a, int b)
{
return a < b ? a : b;
}
/*通用接口函數(shù),實(shí)現(xiàn)對(duì)其他函數(shù)的封裝*/
int Result(pFun fun, int a, int b)
{
return (*fun)(a, b);
}
void main()
{
int a = 3;
int b = 4;
cout<<"Test function pointer: "<<endl;
cout<<"The maximum number between a and b is "<<Result(Max, a, b)<<endl;
cout<<"The minimum number between a and b is "<<Result(Min, a, b)<<endl;
}
2、指向類的成員函數(shù)的指針
類的靜態(tài)成員函數(shù)采用與一般函數(shù)指針相同的調(diào)用方式,而受this指針的影響,類的非靜態(tài)成員函數(shù)與一般函數(shù)指針是不兼容的。而且,不同類的this指針是不一樣的,因此,指向不同類的非靜態(tài)成員函數(shù)的指針也是不兼容的。指向類的非靜態(tài)成員函數(shù)的指針,在聲明時(shí)就需要添加類名。
下面是一個(gè)指向類的成員函數(shù)的指針的使用的例子,包括指向靜態(tài)和非靜態(tài)成員函數(shù)的指針的使用。
#include <iostream.h>
class CA;
/*指向類的非靜態(tài)成員函數(shù)的指針*/
typedef int (CA::*pClassFun)(int, int);
/*指向一般函數(shù)的指針*/
typedef int (*pGeneralFun)(int, int);
class CA
{
public:
int Max(int a, int b)
{
return a > b ? a : b;
}
int Min(int a, int b)
{
return a < b ? a : b;
}
static int Sum(int a, int b)
{
return a + b;
}
/*類內(nèi)部的接口函數(shù),實(shí)現(xiàn)對(duì)類的非靜態(tài)成員函數(shù)的封裝*/
int Result(pClassFun fun, int a, int b)
{
return (this->*fun)(a, b);
}
};
/*類外部的接口函數(shù),實(shí)現(xiàn)對(duì)類的非靜態(tài)成員函數(shù)的封裝*/
int Result(CA* pA, pClassFun fun, int a, int b)
{
return (pA->*fun)(a, b);
}
/*類外部的接口函數(shù),實(shí)現(xiàn)對(duì)類的靜態(tài)成員函數(shù)的封裝*/
int GeneralResult(pGeneralFun fun, int a, int b)
{
return (*fun)(a, b);
}
void main()
{
CA ca;
int a = 3;
int b = 4;
cout<<"Test nonstatic member function pointer from member function:"<<endl;
cout<<"The maximum number between a and b is "<<ca.Result(CA::Max, a, b)<<endl;
cout<<"The minimum number between a and b is "<<ca.Result(CA::Min, a, b)<<endl;
cout<<endl;
cout<<"Test nonstatic member function pointer from external function:"<<endl;
cout<<"The maximum number between a and b is "<<Result(&ca, CA::Max, a, b)<<endl;
cout<<"The minimum number between a and b is "<<Result(&ca, CA::Min, a, b)<<endl;
cout<<endl;
cout<<"Test static member function pointer: "<<endl;
cout<<"The sum of a and b is "<<GeneralResult(CA::Sum, a, b)<<endl;
}
聯(lián)系客服