简体   繁体   中英

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? 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. Did you mean (*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

just do 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)

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] )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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