1. 程式人生 > >一般函式指標和類的成員函式指標

一般函式指標和類的成員函式指標

函式指標是通過指向函式的指標間接呼叫函式。函式指標可以實現對引數型別、引數順序、返回值都相同的函式進行封裝,是多型的一種實現方式。由於類的非靜態成員函式中有一個隱形的this指標,因此,類的成員函式的指標和一般函式的指標的表現形式不一樣。 1、指向一般函式的指標 函式指標的宣告中就包括了函式的引數型別、順序和返回值,只能把相匹配的函式地址賦值給函式指標。為了封裝同類型的函式,可以把函式指標作為通用介面函式的引數,並通過函式指標來間接呼叫所封裝的函式。 下面是一個指向函式的指標使用的例子。
#include <iostream.h>
 
/*指向函式的指標*/
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;
}
 
/*通用介面函式,實現對其他函式的封裝*/
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、指向類的成員函式的指標 類的靜態成員函式採用與一般函式指標相同的呼叫方式,而受this指標的影響,類的非靜態成員函式與一般函式指標是不相容的。而且,不同類的this指標是不一樣的,因此,指向不同類的非靜態成員函式的指標也是不相容的。指向類的非靜態成員函式的指標,在宣告時就需要新增類名。 下面是一個指向類的成員函式的指標的使用的例子,包括指向靜態和非靜態成員函式的指標的使用。
#include <iostream.h>
    
    class CA;
    
    /*指向類的非靜態成員函式的指標*/
    typedef int (CA::*pClassFun)(int, int);
    
    /*指向一般函式的指標*/
    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;
        }
    
        /*類內部的介面函式,實現對類的非靜態成員函式的封裝*/
        int Result(pClassFun fun, int a, int b)
        {
            return (this->*fun)(a, b);
        }
    
    };
    
    /*類外部的介面函式,實現對類的非靜態成員函式的封裝*/
    int Result(CA* pA, pClassFun fun, int a, int b)
    {
        return (pA->*fun)(a, b);
    }
    
    /*類外部的介面函式,實現對類的靜態成員函式的封裝*/
    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;
    }