在下面的代码中,函数指针和我认为的"函数引用"似乎具有相同的语义:
#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 …
Run Code Online (Sandbox Code Playgroud) 所以让我们说我有一个功能:
void foo (int i){
cout << "argument is: " << i << endl;
}
Run Code Online (Sandbox Code Playgroud)
我将此功能传递给:
void function1 (void(callback)(int), int arg){
callback(arg);
}
void function2 (void(*callback)(int), int arg){
callback(arg);
}
Run Code Online (Sandbox Code Playgroud)
这两个功能是否相同?这两者有什么区别吗?