我曾经习惯使用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"));
失败并出现同样的错误。
知道为什么会这样吗?
答案 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"
。