在下面的代码中,函数指针和我认为的“函数引用”似乎具有相同的语义:
#include <iostream>
using std::cout;
void func(int a) {
cout << "Hello" << a << '\n';
}
void func2(int a) {
cout << "Hi" << a << '\n';
}
int main() {
void (& f_ref)(int) = func;
void (* f_ptr)(int) = func;
// what i expected to be, and is, correct:
f_ref(1);
(*f_ptr)(2);
// what i expected to be, and is not, wrong:
(*f_ref)(4); // i even added more stars here like (****f_ref)(4)
f_ptr(3); // everything just works!
// all 4 statements above works just fine
// the only difference i found, as one would expect:
// f_ref = func2; // ERROR: read-only reference
f_ptr = func2; // works fine!
f_ptr(5);
return 0;
}
我在 Fedora/Linux 中使用 gcc 版本 4.7.2
UPDATE
我的问题是:
Why function pointer does not require dereferencing?
Why dereferencing a function reference doesn't result in an error?
- 是否存在我必须使用其中一种而不是另一种的情况?
- Why
f_ptr = &func;
作品?既然 func 应该退化为指针?
While f_ptr = &&func;
不起作用(从隐式转换void *
)
函数和函数引用(即id-表达式这些类型)几乎立即衰减为函数指针,因此表达式func
and f_ref
实际上成为你的情况下的函数指针。您也可以致电(***func)(5)
and (******f_ref)(6)
如果你喜欢。
在您想要的情况下,最好使用函数引用&
- 运算符的工作方式就像它已应用于函数本身一样,例如&func
是相同的&f_ref
, but &f_ptr
是别的东西。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)