[英]function pointer syntax in 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 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;
通常更倾向于采用第二种方式,因为它更加清晰,但是大多数编译器都让用户放弃了第一种方式。
建议通过以下链接查看: http : //en.cppreference.com/w/cpp/language/pointer#Pointers_to_functions
使用时:
int f(int,int);
在main
(或不是函数自变量的任何地方)中,它声明f
为函数,而不是函数的指针。 因此,您不能使用
int f(int,int) = op;
另一方面,
int (*g)(int,int) = op;
声明g
为指向函数的指针。 因此,它起作用。
当将int f(int,int)
用作函数的参数时,等效于使用int (*f)(int, int)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.