anu*_*g86 0 c++ function-pointers
我正在尝试理解通过指向函数指针数组的指针来调用函数的语法。我有一个函数指针数组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
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,func1()并且func2()必须返回值,否则输出其结果将导致未定义的行为
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |