首页 > 解决方案 > 通过指向函数指针数组的指针调用函数

问题描述

我试图理解通过指向函数指针数组的指针调用函数的语法。我有函数指针数组FPTR arr[2]和指向该数组的指针FPTR (vptr)[2]。但是在尝试通过指向数组的指针调用时它给了我一个错误

typedef int (*FPTR)();
int func1(){
        cout<<"func1() being called\n";
}
int func2(){
        cout<<"fun2() being called\n";
}

    FPTR arr[2] = {&func1,&func2};

    FPTR (*vptr)[2];
    vptr=&arr;

    cout<<"\n"<<vptr[0]<<endl;
    cout<<"\n"<<vptr[0]()<<endl;  // ERROR  when trying to call the first function

标签: c++function-pointers

解决方案


vptr指向数组的指针,因此您必须取消对它的引用才能使用该数组。

#include <iostream>
using std::cout;
using std::endl;

typedef int (*FPTR)();
int func1(){
        cout<<"func1() being called\n";
        return 0;
}
int func2(){
        cout<<"fun2() being called\n";
        return 2;
}

int main(){
    FPTR arr[2] = {&func1,&func2};

    FPTR (*vptr)[2];
    vptr=&arr;

    cout<<"\n"<<vptr[0]<<endl;
    cout<<"\n"<<(*vptr)[0]()<<endl;
}

活生生的例子

请注意,func1()andfunc2()必须返回值,否则输出它们的结果会导致未定义的行为


推荐阅读