我正在尝试理解通过指向函数指针数组的指针来调用函数的语法。
我有一个函数指针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
最佳答案
typedef int (*FPTR)();
int func1(){
cout<<"func1() being called\n";
return 1;
}
int func2(){
cout<<"fun2() being called\n";
return 2;
}
FPTR arr[2] = {func1, func2};
// call both methods via array of pointers
cout<<"\n"<< arr[0]() <<endl;
cout<<"\n"<< arr[1]() <<endl;
FPTR (*vptr)[2] = &arr;
// call both methods via pointer to array of pointers
cout<<"\n"<< vptr[0][0]() <<endl;
cout<<"\n"<< vptr[0][1]() <<endl;
// or...
cout<<"\n"<< (*vptr)[0]() <<endl;
cout<<"\n"<< (*vptr)[1]() <<endl;
关于c++ - 通过指向函数指针数组的指针调用函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57848130/