#include <iostream>
using namespace std;
//函数声明
int factorial(int n);
//定义函数指针数据类型:类型名PFactorial
typedef int(*PFactorial)(int n);
int main(int argc,char* argv[])
{
//1.函数显示调用
int m = factorial(3);
cout << "3的阶乘:" << m << endl;
//2.通过定义函数指针调用函数:方式1
int (*pFactorial_1)(int n);//声明函数指针pFactorial_1
pFactorial_1 = factorial;
cout << "4的阶乘:" << pFactorial_1(4) << endl;
cout << "4的阶乘:" << (*pFactorial_1)(4) << endl;
//3.通过定义函数指针调用函数:方式2
int (*pFactorial_2)(int n);//声明函数指针pFactorial_2
pFactorial_2 = &factorial;
cout << "5的阶乘:" << pFactorial_2(5) << endl;
cout << "5的阶乘:" << (*pFactorial_2)(5) << endl;
//4.通过函数指针类型定义一个函数指针来调用函数:方式1
PFactorial pFactorial_3 = factorial;
cout << "6的阶乘:" << pFactorial_3(6) << endl;
cout << "6的阶乘:" << (*pFactorial_3)(6) << endl;
//5.通过函数指针类型定义一个函数指针来调用函数:方式2
PFactorial pFactorial_4 = &factorial;
cout << "7的阶乘:" << pFactorial_4(7) << endl;
cout << "7的阶乘:" << (*pFactorial_4)(7) << endl;
}
//计算阶乘
int factorial(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
else
{
return factorial(n - 1) * n;
}
}
【说明】:
方式1和方式2中对函数指针的赋值方式是等价的。 对于函数指针的访问,pFactorial与(*pFactorial)两种方式也是等价的。
函数名也是一种函数指针,函数名是函数指针常量,函数指针是函数指针变量