C++中的函数指针语法

2022-04-10 00:00:00 function-pointers c++

我只是在学习C++中的函数指针。下面的示例都编译并返回预期的结果,但我被告知示例3是可行的。为什么其他示例仍然有效?

还有一件事看起来很奇怪,与上面的例子相比,f,g,h,i并不是所有的例子都有效。与示例1-8相比,它们为什么不起作用?

int executeOperator1(int a, int b, int f(int,int)){
    return f(a,b);
}

int executeOperator2(int a, int b, int f(int,int)){
    return (*f)(a,b);
}
int executeOperator3(int a, int b, int (*f)(int,int)){
    return f(a,b);
}

int executeOperator4(int a, int b, int (*f)(int,int)){
    return (*f)(a,b);
}

int op(int x, int y){
    return x+y;
}


int main(int argc, char *argv[])
{
    int a = 2, b=3;
    //the following 8 examples compile nicely:
    cout << "a=" << a << " b=" << b << " res=" << executeOperator1(a,b,op) <<endl; //1
    cout << "a=" << a << " b=" << b << " res=" << executeOperator2(a,b,op) <<endl; //2
    cout << "a=" << a << " b=" << b << " res=" << executeOperator3(a,b,op) <<endl; //3
    cout << "a=" << a << " b=" << b << " res=" << executeOperator4(a,b,op) <<endl; //4
    cout << "a=" << a << " b=" << b << " res=" << executeOperator1(a,b,&op) <<endl; //5
    cout << "a=" << a << " b=" << b << " res=" << executeOperator2(a,b,&op) <<endl; //6
    cout << "a=" << a << " b=" << b << " res=" << executeOperator3(a,b,&op) <<endl; //7
    cout << "a=" << a << " b=" << b << " res=" << executeOperator4(a,b,&op) <<endl; //8

    //int f(int,int) = op;  //does not compile
    int (*g)(int,int) = op; //does compile
    //int h(int,int) = &op; //does not compile
    int (*i)(int,int) = &op;//does compile
    return 0;
}

解决方案

函数与数组一样,在作为参数传递给函数时会衰变为指针。例如:接受两个int参数并返回int的函数的类型为int (*) (int, int)
但您也可以将函数作为引用传递,在这种情况下,您的类型将为int (&) (int, int)。 要声明上述函数指针类型的值,只需编写:

typedef int (*FuncType) (int, int);
FuncType myFunc = op; 
// OR
FuncType myFunc = &op;

通常首选第二种方式,因为它更清楚,但大多数编译器允许用户取消第一种样式。

建议访问以下链接: http://en.cppreference.com/w/cpp/language/pointer#Pointers_to_functions

相关文章