指向类方法 QT 的指针向量

Vector of pointers to class methods QT

本文关键字:指针 向量 QT 类方法      更新时间:2023-10-16

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

QVector<void(*)()> m_operationsVector;

然后我有示例类的方法:

QString sampleMethod(QJsonObject &jsonObject, QString delim);

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

m_operationsVector.push_back(sampleMethod);

但不幸的是,在将此指针添加到矢量的过程中,我收到此错误:

error: invalid use of non-static member function

如何解决此问题?

首先,指向类方法的指针定义不同,因此此向量应如下所示:

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

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

QVector<std::function<void()>> m_operationsVector;
operationsVector.push_back([this]() { this->someMethod(); });

第三,当这与JSon相结合时,这看起来很可疑。你在干什么?这看起来像 XY 问题。