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++中的函数指针语法
				
        
 
            
        
             猜你喜欢
        
	     - GDB 不显示函数名 2022-01-01
 - 将 hdc 内容复制到位图 2022-09-04
 - 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
 - OpenGL 对象的 RAII 包装器 2021-01-01
 - DoEvents 等效于 C++? 2021-01-01
 - 将函数的返回值分配给引用 C++? 2022-01-01
 - XML Schema 到 C++ 类 2022-01-01
 - 如何提取 __VA_ARGS__? 2022-01-01
 - 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
 - 哪个更快:if (bool) 或 if(int)? 2022-01-01
 
						
						
						
						
						