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