c++ - C++ 中 void(*)() 和 void(&)() 的区别

标签 c++ pointers

<分区>

在此示例代码中,func1void (*)(int, double) 的类型,funkyvoid(&)(int, double)

#include <iostream>

using namespace std;

void someFunc(int i, double j) {
    cout << i << ":" << j << endl;
} 

int main(int argc, char *argv[]) {

    auto func1 = someFunc; 
    auto& func2 = someFunc;

    cout << typeid(func1).name() << endl;
    cout << typeid(func2).name() << endl;

    func1(10, 20.0);
    func2(10, 30.0);
}

输出显示差异:

PFvidE
FvidE
10:20
10:30

实际上,这两种类型之间有什么区别?

最佳答案

如果您希望能够将指针分配给函数,然后更改该指针指向的内容,请使用 auto fp = func .如果不是,则使用引用 auto& rp = func因为你不能重新分配它:

#include <iostream>
using namespace std;

int funcA(int i, int j) {
    return i+j;
}

int funcB(int i, int j) {
    return i*j;
}

int main(int argc, char *argv[]) {
    auto fp = funcA;
    auto& rp = funcA;

    cout << fp(1, 2) << endl; // 3 (1 + 2)
    cout << rp(1, 2) << endl; // 3 (1 + 2)

    fp = funcB;
    //rp = funcB; // error: assignment of read-only reference 'rp'

    cout << fp(1, 2) << endl; // 2 (1 * 2)

    return 0;
}

我试图想出一个更实际的例子来说明为什么有人会这样做,下面是一些使用指针数组根据用户输入调用函数的代码(arr 的任何元素也可以是在运行时更改为指向另一个函数):

#include <iostream>
using namespace std;

void funcA(int i, int j) {
    std::cout << "0: " << i << ", " << j << endl;
}

void funcB(int i, int j) {
    std::cout << "1: " << i << ", " << j << endl;
}

void funcC(int i, int j) {
    std::cout << "2: " << i << ", " << j << endl;
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        cout << "Usage: ./a.out <val>" << endl;
        exit(0);
    }

    int index = atoi(argv[1]);
    if (index < 0 || index > 2) {
        cout << "Out of bounds" << endl;
        exit(0);
    }

    void(* arr[])(int, int) = { funcA, funcB, funcC };
    arr[index](1, 2);

    return 0;
}

关于c++ - C++ 中 void(*)() 和 void(&)() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30560947/

相关文章:

c++ - 何时在 C++ 中返回指针、标量和引用?

c++ - 返回一个指针数组?

C++ vector<vector<int>> 开头保留大小

.net - C++ 原生与 C++/Cli 性能对比(针对 OpenCV 项目)

c指针数组段错误

c - 在结构中使用寄存器

c - void 指针上的索引

c++ - 维度字符数组之外的额外垃圾值

c++ - CMake : Linking cURL to my project : "cannot find -lcurl"

php - 客户端断开连接后 CSimpleSocket 失败