簡體   English   中英

(C ++ QT)QList僅允許追加常量類對象?

[英](C++ QT) QList only allows appending constant class objects?

我對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追加期間遇到的錯誤

錯誤:從'const MyInt *'到'MyInt *'的無效轉換錯誤:
初始化“ void QList :: append(const T&)[with T = MyInt *]”的參數1

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

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

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 *

您將需要使用:

   QList<const MyInt*> myintarray;

編譯器告訴您現在需要做的所有事情-您試圖將const T*存儲為T*並且不允許從const T*T*隱式轉換。
只需在append()時省略const

我會說您應該將常規MyInt *傳遞到QList :: append中。 “ const T&”表示指針類型-QList承諾不會重新分配您提供的指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM