问题描述
有以下代码:
void a() { }
// function parameter first defined as function, then as pointer to function
void g(void f() = a, void (*d)() = a) {
}
int main(){
void (*z)() = a; // works ok
//void z() = a; error: illegal initializer (only variables can be initialized)
return 0;
}
在函数参数列表中,可以将函数参数定义为函数或指针函数(请参见函数 g
参数列表)。但是在 main
函数中,只有指向函数版本的指针似乎工作。是否有某种方法在块范围中定义一个函数变量(不是函数的指针)(如 g中的
function)? void f()= a
In function parameter list you can define function parameter as a function or as pointer to function (see function g
parameter list). However in main
function only pointer to function version seems to work. Is there some way to define a function variable (not a pointer to function) in block scope (like the void f() = a
variable in g
function)?
推荐答案
C ++中不能有函数类型的变量。你可以有指针或引用的函数,虽然:
You cannot have variables of function type in C++. You can either have pointers or references to functions, though:
typedef void (funtype)();
void call(funtype & f) { f(); } // OK, funtype & == void (&)()
void call(funtype * g) { g(); } // Also OK, funtype * == void (*)()
在某种意义上, 始终通过函数指针调用函数:其值为函数的表达式立即衰减到相应的函数指针。因此在上面的例子中, f()
,(* f)()
, ** f)()
等都是调用函数的有效方法,同样对于 g
也是如此。但是通过引用传递的优点是你仍然可以通过& f
显式地获得函数指针。
In some sense, you always call a function through a function pointer: An expression whose value is a function immediately decays to the corresponding function pointer. So in the above examples, f()
, (*f)()
, (**f)()
and so forth are all valid ways of calling the function, and likewise for g
. But passing by reference has the advantage that you can still get the function pointer explicitly by saying &f
.
这篇关于函数变量而不是指向函数的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!