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);

扫描二维码关注公众号,回复: 4570031 查看本文章

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;  //正确,精确匹配


猜你喜欢

转载自blog.csdn.net/m1m2m3mmm/article/details/79252009