我的类中有方法的指针数组,但我不能调用我的方法.代码如下
I have array of pointers of methods my class, but I cannot call my method. Code are below
#include <iostream>
#include <stdio.h>
#include <stdint.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class FooBar{
public:
typedef void(FooBar::*OnDio)(void);
void OnDio0Irq( void ){
printf("dio0n");
};
void OnDio1Irq( void ){
printf("dio1n");
};
FooBar(){
OnDio dioArray[] = {&OnDio0Irq, &OnDio1Irq};
};
OnDio *dioArray[2];
private:
};
int main(int argc, char* argv[]){
typedef void(FooBar::*OnDio)(void);
void (FooBar::*foo)(void);
OnDio *myPtr;
FooBar *fb = new FooBar();
myPtr = *(&fb->dioArray[0]);
foo = (OnDio &)(myPtr[0]);
(foo)();//me need call fb->dioArray[0]()
(*myPtr)(); // ?
}
如何从数组中调用函数?在我的代码中,我有错误:
[Error]必须使用''或'->'调用指向'foo中成员函数的指针(…)',例如'(…->*foo)(…)'
[Error]必须使用">'或'->'调用指向中成员函数的指针'*myPtr(…)',例如'(…->**myPtr)(…)'
OnDio已经被类型化为指针类型,所以你可能不想要OnDio指针。
此外,您在构造函数中初始化一个本地临时,而不是"this"实例的dioArray。
这个答案也很有用:C++:指向不同函数的成员函数指针数组
这是您的代码,更正为通过指向成员函数的指针调用dio0。
#include <iostream>
#include <stdio.h>
#include <stdint.h>
class FooBar {
public:
typedef void(FooBar::*OnDio)(void);
void OnDio0Irq(void) {
printf("dio0n");
};
void OnDio1Irq(void) {
printf("dio1n");
};
FooBar() {
// declaring a local OnDio array just masks the actual member and then it gets tossed
// need to initialize this instance, not some local temporary
dioArray[0] = &FooBar::OnDio0Irq;
dioArray[1] = &FooBar::OnDio1Irq;
};
OnDio dioArray[2];
private:
};
int main(int argc, char* argv[]) {
// need instance
FooBar fb;
// need pointer to member function
FooBar::OnDio func = fb.dioArray[0];
// call pointer to member function using instance
(fb.*func)();
}
#include <iostream>
#include <stdio.h>
#include <stdint.h>
class FooBar {
public:
typedef void(FooBar::*OnDio)(void);
OnDio dioArray[2];
void OnDio0Irq(void) {
printf("dio0n");
};
void OnDio1Irq(void) {
printf("dio1n");
};
FooBar() {
dioArray[0] = &FooBar::OnDio0Irq;
dioArray[1] = &FooBar::OnDio1Irq;
};
private:
};
int main(int argc, char* argv[]) {
FooBar* fb = new FooBar();
for (int i = 0; i < sizeof(fb->dioArray) / sizeof(fb->dioArray[0]); i++)
{
(fb->*fb->dioArray[i])();
}
}
相关文章:
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 为什么我的 IExtractIcon 处理程序没有被调用?
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- 为什么我的运算符 + 重载尽管是通过引用传递的,但仍调用我的复制构造函数?
- C++ - 为什么我的程序在再次调用函数后关闭?
- 为什么我的向量::擦除调用会抛出"vector subscript out of range"?
- 什么时候可以使用常量装饰调用我的重载函数?
- 我应该提到纯虚函数中的调用约定吗?
- QObject::d eleteLater在我的Qt测试中没有像预期的那样调用
- 提升图:当我的图使用 listS 作为 VertexList 时,如何调用深度优先搜索()?
- 为什么当我做复制和交换习语时不调用我的复制构造函数?
- 我的 cout 上有一个奇怪的输出,它把答案放在第一位,然后在我调用它的地方放一个奇怪的输出.我该怎么办?
- 为什么只有当我的容器有超过 32 个元素时才由 std::sort 调用交换?
- 为什么我的编译器在调用 const getter 函数时抛出"转换丢失(const)限定符"错误?
- 我不知道为什么复制构造函数的调用在 c++ 中不稳定
- 矢量迭代器在尝试调用函数时使我的程序崩溃
- 我可以调用从 main() 覆盖的虚拟函数吗?
- 使用唯一指针调用函数会使我的程序崩溃
- 是否允许调用方对我的 Builder 类使用任何指针类型(包括智能指针)?
- 为什么我的对象声明不调用默认构造函数?