在以下程序中,main函数体之中定义的函数指针ptrWhichFunction满足题主要求!
#include <iostream> //cin, cout, endl
#include <cassert> //assert
using std::cin; using std::cout; using std::endl;
int square(int integer); //平方
int cube(int integer); //立方
int factorial(int integer); //阶乘
int (*whichFunction(int integer, int result))(int); //哪一个函数指针
int main()
{
int integer=0, result=0; //整数,计算结果
while(true)
{
cout<<"Enter two integers (e.g., 3 27): ";
cin>>integer>>result;
int (*(*ptrWhichFunction)(int, int))(int)=&whichFunction;
//指向“哪一个函数指针”的指针
int (*ptrFunction)(int)=(*ptrWhichFunction)(integer, result);
//指向“哪一个函数”的指针
if(ptrFunction!=0)
assert(ptrFunction(integer)==result);
else
break;
}
return 0;
}
int square(int integer){ return integer*integer; }
int cube(int integer){ return integer*integer*integer; }
int factorial(int integer)
{
int result=1;
while(integer>1)
result*=integer--;
return result;
}
int (*whichFunction(int integer, int result))(int)
{
int (*functions[])(int)={&square, &cube, &factorial}; //函数指针数组
const size_t length=sizeof(functions)/sizeof(functions[0]); //数组长度
const char* names[length]={"square", "cube", "factorial"}; //名称数组
int results[length]={square(integer), cube(integer), factorial(integer)}; //结果数组
for(size_t index=0; index<length; index++)
if(result==results[index])
{
cout<<names[index]<<" of "<<integer<<" is "<<result<<endl;
return functions[index];
}
return 0;
}
执行结果截图如下:

发布于 2023-06-28 12:26・IP 属地辽宁