一、指针函数
指针函数就是返回指针的函数。
#include<iostream>
#include<string>
using namespace std;
int *getchar(char c)
{
switch(c)
{
case'A':cout << "Apple" << endl; break;
case'B':cout << "Banana" << endl; break;
case'C':cout << "Cat" << endl; break;
case'D':cout << "Dog" << endl; break;
default:cout << "None" << endl;
}
return 0;
}
int main()
{
char input;
while (1)
{
cout << "请输入一个大写字母:" << endl;
cin >> input;
getchar(input);
}
system("pause");
return 0;
}
其实这时候,把getchar()函数前面的*去掉,结果是一样的。只是意义不同。
二、函数指针
即指向函数的指针
int test(int a)
{
return a;
}
int main(int argc, const char * argv[])
{
int (*fp)(int a);
fp = test;
cout<<fp(2)<<endl;
return 0;
}
三、函数指针作为参数
vector<int> map(const vector<int> &v,int (*f)(int n))
{
vector<int> res(v.size(),0);
for(unsigned int i=0;i<v.size();i++)
{
res[i]=f(v[i]);
}
return res;
}
int func(int n)
{
return n*n;
}
int func2(int n)
{
return n*n*n;
}
//调用map()函数时
vector<int> test_vector{1,2,3,4,5};
vector<int> re1=map(test_vector,func);//re1将会 得到{1,4,9,16,25}
四、返回指向函数指针的函数
#include <iostream>
using namespace std;
int funTwo(int a, int b)
{
return a * b;
}
// funOne是一个函数,带有一个int型参数,它返回一个指向函数的指针
// 这个指向函数的指针指向一个返回int型,并带有两个int型的形参的函数
int (*funOne(int number))(int a, int b)
{
cout<<number<<endl;
return funTwo;
}
int main()
{
cout<<funOne(5)(3, 10)<<endl;
system("pause");
return 0;
}//结果输出5,30