2010-01-07 55 views
0

我对QT很新。我一直在为它乱搞一个星期。我碰到一个错误来了,而我是想自定义数据类型添加到的QList像这样(C++ 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)); 

和我的敏类是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*]'

如果任何人都可以指出我做错了什么,那就太棒了。

回答

7

所以你创建的列表:

QList<MyInt*> myintarray;

然后您稍后尝试追加

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

的问题是新的const MyInt正在创建一个const MyInt *,你不能指定给MyInt *,因为它失去了常量。

你要么需要改变你的QList保持常量MyInts像这样:

QList<const MyInt*> myintarray;

,或者你需要不改变你的追加到创建一个const敏*:

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

你将选择的方法将取决于你想如何使用你的QList。你只想要const MyInt *,如果你永远不想改变你的MyInt

+0

更有意义......谢谢 – colorfulgrayscale 2010-01-07 23:07:49

0

编译器告诉你所有你需要现在 - 你想存储const T*作为T*和隐式转换从const T*T*是不允许的。
只需在append()时省略const即可。

+0

它的工作数据,非常感谢! – colorfulgrayscale 2010-01-07 23:06:18

0

我会说你应该只是将一个普通的MyInt *传递给QList :: append。 “const T &”指向指针类型 - QList有希望不重新分配您提供的指针。

3

您可能需要使用:

QList<const MyInt*> myintarray; 
+0

会说你不想保存const指针,因为你会泄漏(由于删除不工作)。但是我查了一下,令我惊讶的是你确实可以删除一个const指针。不知道我是否喜欢它,但是......每天我都会学到一些新的东西! – HostileFork 2010-01-07 22:56:23

+0

好的,如果我这样做了,那么这个对象是否可变? 我想遍历该列表并编辑一些值,但这是不可能的,因为这会丢弃'const'限定符。建议? – colorfulgrayscale 2010-01-07 23:03:33