[英]array of pointer to functions c++
有人能告诉我这段代码有什么问题吗?! visual studio告诉*的操作数必须是一个指针......(在我们称之为操作的行中)...有人能说出如何准确地声明一个指向函数的指针数组吗? 我真的很困惑。
#include<iostream>
#include<conio.h>
using namespace std;
int power(int x)
{
return(x*x);
}
int factorial(int x)
{
int fact=1;
while(x!=0)
fact*=x--;
return fact;
}
int multiply(int x)
{
return(x*2);
}
int log(int x)
{
int result=1;
while(x/2)
result++;
return result;
}
//The global array of pointer to functions
int(*choice_array[])(int)={power,factorial,multiply,log};
int operation(int x,int(*functocall)(int))
{
int res;
res=(*functocall)(x);
return res;
}
int main()
{
int choice,number;
cout<<"Please enter your choice : ";
cin>>choice;
cout<<"\nPlease enter your number : ";
cin>>number;
cout<<"\nThe result is :"<<operation(number,(*choice_array[choice](number)));
}
问题是(*choice_array[choice](number))
不是函数本身,而是函数调用的结果。 你的意思是(*choice_array[choice])
?
operation接受一个函数作为参数,但是(*choice_array[choice](number))
是一个int,因为它将choice-array[choice]
应用于number
只做operation(number, choice_array[choice])
编辑:不想说错,但在我看来
*(choice_array[choice])
(choice_array[choice])
是相同的,(意味着指向函数IS的指针(可以用作调用)函数,你不能“取消引用”它)
这个电话
operation(number, (*choice_array[choice](number)))
是无效的。
您必须提供指向函数的指针作为第二个参数。 要么写
operation(number, choice_array[choice] )
要么
operation(number, *choice_array[choice] )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.