在下面的代码中,函数指针和我认为的“函数引用”似乎具有相同的语义:
#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。
更新
我的问题是:
为什么函数指针不需要解引用?为什么解引用函数引用不会导致错误?- 有没有情况必须选择其中之一?
- 为什么
f_ptr = &func;
有效?因为func应该被衰减成一个指针吗?
而f_ptr = &&func;
无效(来自void *
的隐式转换)
void (*&f)(void)
这样的东西作为函数参数 -*
和&
一起使用.. 怎么回事? - Johnf(1)
,而不是更繁琐的(&f)(1)
)。 - Kerrek SBint x[]
(以及int x[10]
)等同于int *x
;由于按值接收C数组是不合法的,所以他们允许使用数组声明语法作为接收指针的语法糖。 - ShadowRanger