您的位置:首页 > 编程语言 > C语言/C++

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

2017-10-12 16:06 423 查看
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;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++作业