【问题标题】:Calling C++ member function pointer from a struct从结构调用 C++ 成员函数指针
【发布时间】:2011-10-15 06:40:58
【问题描述】:

我找到了有关调用 C++ 成员函数指针和调用结构中的指针的信息,但是我需要调用结构内部存在的成员函数指针,并且我无法获得正确的语法。我在 MyClass 类的方法中有以下 sn-p:

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);')

移动这些括号会导致语法错误,建议使用 .* 或 ->* 在这种情况下两者都不起作用。有谁知道正确的语法吗?

【问题讨论】:

标签: c++ function-pointers


【解决方案1】:

用途:

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

测试和编译;)

【讨论】:

  • 啊完美!感谢您的回复,上面的答案提供了推理。
【解决方案2】:

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

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

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

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

【讨论】:

  • 感谢您的解释。以下答案有效(括号包括“this”而不是“functionMap”。感谢您的回复。
  • 我不确定它是否需要这些。虽然对于那个问题,我可能会尝试不同的解决方案,例如只使用 if,或者如果需要更大的灵活性,则需要某种命令模式。
猜你喜欢
  • 1970-01-01
  • 2010-11-23
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
  • 2013-01-26
  • 2015-12-05
  • 1970-01-01
  • 2010-12-01
相关资源
最近更新 更多