简体   繁体   English

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

[英]array of pointer to functions c++

Can someone tell me what is wrong with this code?! 有人能告诉我这段代码有什么问题吗?! visual studio tells the operand of * must be a pointer... (in line that we call operation)... can someone tell how exactly declaring an array of pointer to functions is? visual studio告诉*的操作数必须是一个指针......(在我们称之为操作的行中)...有人能说出如何准确地声明一个指向函数的指针数组吗? I'm really confused. 我真的很困惑。

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

The problem is that (*choice_array[choice](number)) isn't a function itself but a result of function call. 问题是(*choice_array[choice](number))不是函数本身,而是函数调用的结果。 Did you mean (*choice_array[choice]) ? 你的意思是(*choice_array[choice])

operation takes a function as argument, but (*choice_array[choice](number)) is an int, cuz it's applying choice-array[choice] to number operation接受一个函数作为参数,但是(*choice_array[choice](number))是一个int,因为它将choice-array[choice]应用于number

just do operation(number, choice_array[choice]) 只做operation(number, choice_array[choice])

EDIT : don't want to say something wrong, but it seems to me that 编辑:不想说错,但在我看来

*(choice_array[choice])

(choice_array[choice])

are the same, (meaning pointer to the function IS (can be used as a call to) the function, and you cant "dereference" it) 是相同的,(意味着指向函数IS的指针(可以用作调用)函数,你不能“取消引用”它)

This call 这个电话

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

is invalid. 是无效的。

You have to supply a pointer to a function as second argument. 您必须提供指向函数的指针作为第二个参数。 Either write 要么写

operation(number, choice_array[choice] )

or 要么

operation(number, *choice_array[choice] )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM