C++primeer 6.7节练习(函数指针,函数指针形参)

6.54

#include <iostream>  
#include <string>
#include <vector>
using namespace std;

/*函数指针*/
int test(int a, int b);
/*定义一个指向test函数类型的指针 pf*/
int(*pf)(int, int); 
/*用decltype和typedef定义此函数类型指针*/
typedef decltype(test) *pf1;
/*或者这样写*/
typedef int(*pf2)(int, int);
/*定义一个vector对象,其元素是指向此函数类型的指针*/
vector<pf1> Vec;

/*或是这样*/
vector<decltype(test) *> Vec1;

6.56

#include <iostream>  
#include <string>
#include <vector>
using namespace std;

/*函数指针*/
int Sum(int a, int b)
{
	return a + b;
}
int Dec(int a, int b)
{
	return a - b;
}
int Mul(int a, int b)
{
	return a * b;
}
int Div(int a, int b)
{
	return a / b;
}

/*定义一个指向test函数类型的指针 pf*/
int(*pf)(int, int);
/*用decltype和typedef定义此函数类型指针*/
typedef decltype(Sum) *pf1;
/*或者这样写*/
typedef int(*pf2)(int, int);
/*定义一个vector对象,其元素是指向此函数类型的指针*/
vector<pf1> Vec{Sum,Dec,Mul,Div};

/*或是这样*/
vector<decltype(Sum) *> Vec1{Sum,Dec,Mul,Div};

/*函数指针形参*/
void Compute1(int j, int k, pf1 PF1)
{
	cout << PF1(j,k) << endl;
}
/*或者这样写*/
void Compute2(int j, int k, int(*PF2)(int, int))
{
	cout << PF2(j, k) << endl;
}
int main()
{	
	int A = 5, B = 10;
	cout << "采用Compute1" << endl;
	cout << "加减乘除结果为: " << endl;
	for (auto p : Vec)
		Compute1(A, B, p);
	cout << "采用Compute2" << endl;
	cout << "加减乘除结果为: " << endl;
	for (auto p1 : Vec)
		Compute2(A, B, p1);
	system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值