c++ - 通过指向函数指针数组的指针调用函数
问题描述
我试图理解通过指向函数指针数组的指针调用函数的语法。我有函数指针数组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
解决方案
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()
必须返回值,否则输出它们的结果会导致未定义的行为
推荐阅读
- html - 为什么在 Angular 10 中双向绑定对我不起作用?
- amazon-web-services - 如何提高 FFMPEG 输出到 S3 存储桶的速度
- angular - 渲染数百页时如何限制 Angular Universal
- json - 如何在CI 4中将qr代码作为图像png返回给ajax
- node.js - 如何在 sequelize 中加入 4 个或更多表?
- c# - 删除外键相同但主键不同的行互不影响
- haskell - 在ghci中自动将`[Char]`显示为`String`?
- android - 当用户停止拖动 [KOTLIN] 时在 Material Slider 中显示标签
- python - 在 python 中如何绘制洛伦兹曲线?
- redis - MacOS 11 上的 Redis 服务器崩溃