指针函数、函数指针及函数指针作为参数、返回指向函数指针的函数

一、指针函数
指针函数就是返回指针的函数。

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值