C++中的函数指针语法 [英] function pointer syntax in c++

查看:51
本文介绍了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

这篇关于C++中的函数指针语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆