C ++中void(*)()和void(&)()之间的区别 [英] Difference between void(*)() and void(&)() in C++

查看:115
本文介绍了C ++中void(*)()和void(&)()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In this example code, func1 is the type of void (*)(int, double) and funky is the type of void(&)(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

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

Practically, what is the difference between the two types?

推荐答案

如果您希望能够为函数分配一个指针,然后在以后更改该指针指向的内容,则可以使用auto fp = func.如果没有,请使用参考auto& rp = func,因为您无法重新分配它:

If you wanted to be able to assign a pointer to a function and then later change what that pointer points to then use auto fp = func. If not then use a reference auto& rp = func since you cannot reassign it:

#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的任何元素也可以是在运行时更改为指向另一个函数):

I was trying to come up with a more practical example of why anyone would ever do this, below is some code that uses an array of pointers to call a function based on user input (any element of arr could also be changed during run time to point to another function):

#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 ++中void(*)()和void(&amp;)()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆