呼叫 C++结构体中的成员函数指针
我找到了有关调用 C++ 成员函数指针和调用结构中的指针的信息,但我需要调用结构内部存在的成员函数指针,但我无法获得正确的语法。我在 MyClass 类的方法中有以下代码片段:
void MyClass::run() {
struct {
int (MyClass::*command)(int a, int b);
int id;
} functionMap[] = {
{&MyClass::commandRead, 1},
{&MyClass::commandWrite, 2},
};
(functionMap[0].MyClass::*command)(x, y);
}
int MyClass::commandRead(int a, int b) {
...
}
int MyClass::commandWrite(int a, int b) {
...
}
这给了我:
error: expected unqualified-id before '*' token
error: 'command' was not declared in this scope
(referring to the line '(functionMap[0].MyClass::*command)(x, y);')
移动这些括号会导致语法错误,建议使用 .* 或 ->* 在这种情况下这两种方法都不起作用。有人知道正确的语法吗?
I have found information on calling C++ member function pointers and calling pointers in structs, but I need to call a member function pointer that exists inside of a structure, and I have not been able to get the syntax correct. I have the following snippet inside a method in class MyClass:
void MyClass::run() {
struct {
int (MyClass::*command)(int a, int b);
int id;
} functionMap[] = {
{&MyClass::commandRead, 1},
{&MyClass::commandWrite, 2},
};
(functionMap[0].MyClass::*command)(x, y);
}
int MyClass::commandRead(int a, int b) {
...
}
int MyClass::commandWrite(int a, int b) {
...
}
This gives me:
error: expected unqualified-id before '*' token
error: 'command' was not declared in this scope
(referring to the line '(functionMap[0].MyClass::*command)(x, y);')
Moving those parenthesis around results in syntax errors recommending using .* or ->* neither of which work in this situation. Does anyone know the proper syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用:
已测试并编译;)
Use:
Tested and compiles ;)
我还没有编译任何代码,但仅通过查看它,我就可以发现您遗漏了一些东西。
MyClass::
。this
指针传递给函数(如果它们使用任何实例数据),这意味着您需要一个MyClass
实例来调用它。(经过一番研究)看起来你需要做这样的事情(也感谢@VoidStar):
I haven't compiled any code, but just from looking at it I can see you're missing a few things.
MyClass::
from where you call the function pointer.this
pointer to the functions (if they use any instance data), so that means you need an instance ofMyClass
to call it.(After a bit of research) It looks like you need to do something like this (also thanks to @VoidStar):