一般函數(shù)指針和類的成員函數(shù)指針深入解析
函數(shù)指針是通過指向函數(shù)的指針間接調(diào)用函數(shù)。函數(shù)指針可以實現(xiàn)對參數(shù)類型、參數(shù)順序、返回值都相同的函數(shù)進行封裝,是多態(tài)的一種實現(xiàn)方式。由于類的非靜態(tài)成員函數(shù)中有一個隱形的this指針,因此,類的成員函數(shù)的指針和一般函數(shù)的指針的表現(xiàn)形式不一樣。
1、指向一般函數(shù)的指針
函數(shù)指針的聲明中就包括了函數(shù)的參數(shù)類型、順序和返回值,只能把相匹配的函數(shù)地址賦值給函數(shù)指針。為了封裝同類型的函數(shù),可以把函數(shù)指針作為通用接口函數(shù)的參數(shù),并通過函數(shù)指針來間接調(diào)用所封裝的函數(shù)。
下面是一個指向函數(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ù),實現(xiàn)對其他函數(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ù)的指針的使用的例子,包括指向靜態(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ù),實現(xiàn)對類的非靜態(tài)成員函數(shù)的封裝*/
int Result(pClassFun fun, int a, int b)
{
return (this->*fun)(a, b);
}
};
/*類外部的接口函數(shù),實現(xiàn)對類的非靜態(tài)成員函數(shù)的封裝*/
int Result(CA* pA, pClassFun fun, int a, int b)
{
return (pA->*fun)(a, b);
}
/*類外部的接口函數(shù),實現(xiàn)對類的靜態(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;
}
相關(guān)文章
C++異步數(shù)據(jù)交換實現(xiàn)方法介紹
這篇文章主要介紹了C++異步數(shù)據(jù)交換實現(xiàn)方法,異步數(shù)據(jù)交換,除了阻塞函數(shù) send() 和 recv() 之外,Boost.MPI 還支持與成員函數(shù) isend() 和 irecv() 的異步數(shù)據(jù)交換2022-11-11

