【问题标题】:Vector of pointers to class methods QT指向类方法 QT 的指针向量
【发布时间】:2017-10-16 21:07:31
【问题描述】:

如何创建指向类方法的指针向量?我将向量作为类的成员(向量必须存储具有不同返回值和签名的方法的指针):

QVector<void(*)()> m_operationsVector;

然后我有示例类的方法:

QString sampleMethod(QJsonObject &jsonObject, QString delim);

我正在尝试将此方法的指针添加到向量:

m_operationsVector.push_back(sampleMethod);

但不幸的是,在将这个指针添加到向量的过程中,我收到了这个错误:

error: invalid use of non-static member function

我该如何解决这个问题?

【问题讨论】:

  • 如果 Foo 是你的班级,那么你可以尝试如下:QVector&lt;void(const Foo&amp;)&gt; m_operationsVector;m_operationsVector.push_back(&amp;Foo::processSetBlindStateRequest);
  • vector 必须存储具有不同返回值和签名的方法指针,你如何决定如何调用它们?
  • 你考虑过使用信号/槽吗?
  • 决定我将使用例如 QPair 并且我将按键搜索方法指针。你能解释一下我的问题是如何使用信号/插槽的吗?

标签: c++ qt pointers vector


【解决方案1】:

首先指向类方法的指针定义不同,所以这个向量应该是这样的:

QVector<void (A::*)()> m_operationsVector;

其次,在 C++11 中使用std::function 和 lambdas 更方便:

QVector<std::function<void()>> m_operationsVector;

operationsVector.push_back([this]() { this->someMethod(); });

第三,当它与 JSon 结合使用时,这看起来很可疑。你在做什么?这看起来像XY Problem

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 2011-08-04
    • 2010-12-05
    • 2010-09-08
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多