指向函数c ++的指针数组

时间:2015-03-04 16:01:06

标签: 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)));
}

3 个答案:

答案 0 :(得分:0)

问题是(*choice_array[choice](number))不是函数本身,而是函数调用的结果。 您的意思是(*choice_array[choice])吗?

答案 1 :(得分:0)

操作将函数作为参数,但(*choice_array[choice](number))是一个int,因为它将choice-array[choice]应用于number

只做operation(number, choice_array[choice])

编辑:不想说错话,但在我看来

*(choice_array[choice])

(choice_array[choice])

是相同的,(意味着指向函数IS的指针(可以用作对函数的调用),你不能解除&#34;取消引用&#34; it)

答案 2 :(得分:0)

此次电话

operation(number, (*choice_array[choice](number)))

无效。

您必须提供指向函数的指针作为第二个参数。写下

operation(number, choice_array[choice] )

operation(number, *choice_array[choice] )