呼叫 C++结构体中的成员函数指针

发布于 2024-12-09 17:30:43 字数 758 浏览 0 评论 0原文

我找到了有关调用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心清如水 2024-12-16 17:30:43

使用:

(this->*functionMap[0].command)(x, y);

已测试并编译;)

Use:

(this->*functionMap[0].command)(x, y);

Tested and compiles ;)

梦一生花开无言 2024-12-16 17:30:43

我还没有编译任何代码,但仅通过查看它,我就可以发现您遗漏了一些东西。

  • 从调用函数指针的位置删除 MyClass::
  • 需要将 this 指针传递给函数(如果它们使用任何实例数据),这意味着您需要一个 MyClass 实例来调用它。

(经过一番研究)看起来你需要做这样的事情(也感谢@VoidStar):

(this->*(functionMap[0].command)(x, y));

I haven't compiled any code, but just from looking at it I can see you're missing a few things.

  • Remove the MyClass:: from where you call the function pointer.
  • Need to pass the this pointer to the functions (if they use any instance data), so that means you need an instance of MyClass to call it.

(After a bit of research) It looks like you need to do something like this (also thanks to @VoidStar):

(this->*(functionMap[0].command)(x, y));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文