C++中的函数指针语法

function pointer syntax in c++

我正在学习 C++ 中的函数指针。以下示例全部编译并 return 预期结果,但我被告知示例 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 f(int,int);

main 中(或任何不是函数参数的地方),它声明 f 是一个函数,而不是指向函数的指针。因此,您不能使用

int f(int,int) = op;

另一方面,

int (*g)(int,int) = op;

声明 g 为指向函数的指针。因此,它有效。

int f(int,int)作为函数的参数时,相当于sing int (*f)(int, int)

您的所有示例都有效,因为所谓的 指针衰减 规则很棒。函数名 衰减 指向几乎所有上下文中的函数指针。 (这里的衰减意味着原始类型信息丢失,剩下的就是指针。数组在某些情况下也会衰减为指针)。

所以你所有的例子在语义上都是一样的,我不会称它们为 preferred.

为了好玩,这也可以编译:

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

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

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

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

建议阅读以下内容link: http://en.cppreference.com/w/cpp/language/pointer#Pointers_to_functions