喂,
我正在设置一个对象来获得它的QML.在这个对象定义中,我得到了
(location_in_my_computer):25: candidate constructor
not viable: no known conversion from 'QList<QString>' to 'QList<const QString> &'
for 10th argument GroupObject(...,
^在我的代码中,我使用了这个类(最小的例子):
class GroupObject : public QObject
{
public:
GroupObject(QObject *parent=0);
GroupObject(
QList<const QString> &tags, QObject *parent=0);
QList<const QString> tags();
void setTags(QList<const QString> &tags);
private:
QList<QString> m_tags;
}; 及其执行情况:
#include "groupobject.h"
GroupObject::GroupObject( QList<const QString> &tags, QObject *parent) QObject(parent),
m_tags(tags){
}
QList<const QString> GroupObject::tags()
{
return m_tags;
}
void GroupObject::setTags(QList<const QString> &tags)
{
if(tags != m_tags){
m_tags = tags;
}
}然后调用一个QList of GroupObject,如下所示:
QList<QString> tags;
QList<QObject*> dataList;
dataList.append( new GroupObject( tags ));我怎么能用正确的概念来做这件事呢?
谢谢
发布于 2015-09-12 15:26:11
tags的类型是QList<QString>,但是GroupObject收集器接受QList<const QString>。
实际上,用于const的QString修饰符在QList中没有任何意义,因为它不能防止QList修改。它只是拒绝修改QList项。在这种情况下,您甚至不能在QList初始化期间复制这样的一个QList项。
因此,要编译代码,必须通过QList<const QString>更改QList<QString>。在某些地方,您也可能希望防止修改实际的QList对象,例如:
// do not allow GroupObject(...) to change external 'tags' instance
GroupObject(const QList<QString> &tags, QObject *parent=0);
// return reference to internal object field and
// do not allow callers to use that reference for changing that internal field
// it does not change instance of GroupObject, so
// there is 'const' modifier of the member function.
const QList<QString>& tags() const;
// or provide full copy of returned object
QList<QString> tags() const;
// do not allow to change external 'tags' inside 'setTags()'
void setTags(const QList<QString> &tags);顺便说一句,Qt中有QStringList类用于QString列表,它提供了额外的功能。
发布于 2015-09-12 15:48:37
如果您不需要通过值传递它,那么QList<QObject*> dataList是不必要的。QObject也是对象的拥有容器。因此,您还可以写:
class F {
QObject data;
...
void foo() {
QStringList tags = ...;
new GroupObject(tags, &data);
...
}
void bar() {
// iterate all data objects
for (auto obj : data.children()) {
auto group = qobject_cast<GroupObject>(obj);
if (group) { qDebug() << group.tags(); continue; }
...
}
}
}通过利用QObject作为其他对象的拥有容器,您不必担心资源泄漏。它将删除它拥有的所有孩子。因为您按值保存data,所以甚至不需要编写析构函数。利用编译器为您管理资源,它擅长:)
https://stackoverflow.com/questions/32537945
复制相似问题