【问题标题】:error: C2664: 'QXmlStreamWriter::writeAttributes' : cannot convert parameter 1 from 'QVector<T>' to 'const QXmlStreamAttributes &'错误:C2664:“QXmlStreamWriter::writeAttributes”:无法将参数 1 从“QVector<T>”转换为“const QXmlStreamAttributes &”
【发布时间】:2014-11-25 17:20:10
【问题描述】:

我习惯于使用QStringList() &lt;&lt; "a" &lt;&lt; "b" 来快速构造一个QStringList 以传递给函数,但是当我尝试使用QXmlStreamAttributes 时,它不起作用。

这段代码编译:

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&lt;QXmlStreamAttribute&gt;

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

失败并出现同样的错误。

知道为什么会这样吗?

【问题讨论】:

    标签: c++ qt compiler-errors


    【解决方案1】:

    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();
    

    或以其他方式使用&lt;&lt;

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

    两种情况下的输出都是"a"

    QXmlStreamAttributesQStringListQVector

    【讨论】:

    • 所以QXmlStreamAttributes 不会自动继承运算符
    • @sashoalm 我编辑了我的答案并添加了更好的解释,请参阅。
    猜你喜欢
    • 1970-01-01
    • 2021-02-14
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    相关资源
    最近更新 更多