1. 程式人生 > >C++中的函式指標

C++中的函式指標

1. 普通函式指標

typedef double(*ptrFunc)(int, int);

double add(int a, int b);

double sub(int a, int b);

double mul(int a, int b);

double divf(int a, int b);

double add(int a, int b)
{
return a + b;
}
double sub(int a, int b)
{
return a - b;
}
double mul(int a, int b)
{
return a * b;
}
double divf(int a, int b)
{

return a / b;
}

呼叫:

ptrFunc myAdd = &add;
cout << myAdd(100, 132) << endl;
ptrFunc myDiv = &divf;
cout << myDiv(243, 17) << endl;

2. 函式指標做函式形參

//函式指標做引數的
typedef string (*ptrStrFunc)(const string& left, const string& right);

string strAdd(const string& left, const string& right);

string strOperator(const string& left, const string& right, ptrStrFunc tmp);

string strAdd(const string& left, const string& right)
{
return left + right;
}


string strOperator(const string& left, const string& right, ptrStrFunc tmp)
{
return tmp(right, left);
}

呼叫過程:

//函式指標做函式引數
ptrStrFunc myStrAdd = &strAdd;
cout << strOperator(" hello ", " world ", myStrAdd) << endl;

3. 函式指標做函式返回值

//函式指標做函式返回值
ptrStrFunc funcPtrReturn(const string& left, const string& right);

ptrStrFunc funcPtrReturn(const string& left, const string& right)
{
cout << strOperator(left, right, &strAdd) << endl;
return strAdd;
}

呼叫過程:

//函式指標做返回值
ptrStrFunc pf = funcPtrReturn(" I ", " love ");
cout << pf(" hello ", " world ") << endl;

4. 函式指標指向過載函式,必須精確匹配

void ff(vector<double> vec) {cout << "ff(vector<double>)" << endl; }

void ff(unsigned int x) {cout << "ff(unsigned int)" << endl; }

呼叫:

void (*pf)(int) = &ff; //錯誤:int型別的函式指標不能指向unsigned型別

void (*pf)(unsigned int) = &ff;  //正確

double (*pf)(vector<double>) = &ff;  //錯誤:返回值是double的函式指標,不能指向返回值為void的函式

void (*pf)(vector<double>) = &ff;  //正確,精確匹配