错误:C2664:'QXmlStreamWriter :: writeAttributes':无法将参数1从'QVector <t>'转换为'const QXmlStreamAttributes&amp;'</t>

时间:2014-11-25 17:20:11

标签: c++ qt compiler-errors

我曾经习惯使用QStringList() << "a" << "b"成语来快速构建一个QStringList来传递给一个函数,但是当我用QXmlStreamAttributes尝试它时,它没有用。< / p>

此代码编译:

QXmlStreamAttributes attributes;
attributes << QXmlStreamAttribute("a", "b");
writer.writeAttributes(attributes);

但是这个失败了:

writer.writeAttributes(QXmlStreamAttributes() << QXmlStreamAttribute("a", "b"));

失败并显示错误:

C:\Workspace\untitled5\mainwindow.cpp:18: error: C2664: 'QXmlStreamWriter::writeAttributes' : cannot convert parameter 1 from 'QVector<T>' to 'const QXmlStreamAttributes &'
with
[
    T=QXmlStreamAttribute
]
Reason: cannot convert from 'QVector<T>' to 'const QXmlStreamAttributes'
with
[
    T=QXmlStreamAttribute
]
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

我注意到的另一件事:

此代码编译:

QVector<QXmlStreamAttribute> v1 = (QVector<QXmlStreamAttribute>() << QXmlStreamAttribute("a", "b"));

但是这个没有,即使QXmlStreamAttributes继承自QVector<QXmlStreamAttribute>

QXmlStreamAttributes v2 = (QXmlStreamAttributes() << QXmlStreamAttribute("a", "b"));

失败并出现同样的错误。

知道为什么会这样吗?

1 个答案:

答案 0 :(得分:2)

QStringList

operator<<(const QString & str)

QVector

QVector<T> &    operator<<(const T & value)

所以你的

QVector<QXmlStreamAttribute> v1 = (QVector<QXmlStreamAttribute>() << QXmlStreamAttribute("a", "b"));

成功编译。

但是你的错误是QXmlStreamAttributes没有复制构造函数,但是你尝试使用它,所以你有2个解决方案:

使用append

QXmlStreamAttributes v2;
v2.append(QXmlStreamAttribute("a", "b"));
qDebug()<< v2.first().name();

或以某种不同的方式使用<<

QXmlStreamAttributes v2;
v2 << QXmlStreamAttribute("a", "b");
qDebug()<< v2.first().name();

两种情况下的输出均为"a"

QXmlStreamAttributes QStringList QVector