(C ++ QT)QList仅允许追加常量类对象?

发布于 2020-03-04 23:37:28

我对QT很陌生。我已经把它弄乱了一个星期。尝试将自定义数据类型添加到Qlist时遇到错误

QObject parent;

QList<MyInt*> myintarray;

myintarray.append(new const MyInt(1,"intvar1",&parent));
myintarray.append(new const MyInt(2,"intvar2",&parent));
myintarray.append(new const MyInt(3,"intvar3",&parent));

我的MyInt类是int的简单包装,看起来像这样

#ifndef MYINT_H
#define MYINT_H

#include <QString>
#include <QObject>

class MyInt : public QObject
{ 
 Q_OBJECT

 public:

MyInt(const QString name=0, QObject *parent = 0);
MyInt(const int &value,const QString name=0, QObject *parent = 0);
MyInt(const MyInt &value,const QString name=0,QObject *parent = 0);
int getInt() const;

public slots:
void setInt(const int &value);
void setInt(const MyInt &value);

signals:
 void valueChanged(const int newValue);

private:
int intStore;

};

#endif

我在Qlist追加期间遇到的错误

error: invalid conversion from 'const MyInt*' to 'MyInt*' error:
initializing argument 1 of 'void QList::append(const T&) [with T = MyInt*]'

如果有人能指出我在做什么错,那将是很棒的。

查看更多

关注者
0
被浏览
565
1 个回答
杰森T.
杰森T. 2020-03-04
这家伙很懒,什么也没写!

因此,您创建了以下列表:

QList<MyInt*> myintarray;

然后您稍后尝试附加

myintarray.append(new const MyInt(1,"intvar1",&parent));

问题是新的const MyInt正在创建const MyInt ,您不能将其分配给MyInt ,因为它会失去constness。

您要么需要更改QList来保存const MyInts,如下所示:

QList<const MyInt*> myintarray;

或者您不需要通过将追加更改为以下内容来创建const MyInt *:

myintarray.append(new MyInt(1,"intvar1",&parent));

您将选择的方法将完全取决于您要如何使用QList。如果您不想更改MyInt中的数据,则只需要const MyInt *

撰写答案

请登录后再发布答案,点击登录

发布
问题

分享
好友

手机
浏览

扫码手机浏览