function pointer syntax in c++(C++中的函数指针语法)
                            本文介绍了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++中的函数指针语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:C++中的函数指针语法
				
        
 
            
        基础教程推荐
             猜你喜欢
        
	     - 这个宏可以转换成函数吗? 2022-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				