相关疑难解决方法(0)

函数指针与函数引用

在下面的代码中,函数指针和我认为的"函数引用"似乎具有相同的语义:

#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)

c++ pointers function-pointers reference function

23
推荐指数
2
解决办法
7287
查看次数

回调函数:void(*func)(int)和void(func)(int)之间的区别

所以让我们说我有一个功能:

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)

这两个功能是否相同?这两者有什么区别吗?

c c++ function callback

5
推荐指数
1
解决办法
899
查看次数

标签 统计

c++ ×2

function ×2

c ×1

callback ×1

function-pointers ×1

pointers ×1

reference ×1