【问题标题】:QJsonValueRef vs. QJsonValueQJsonValueRef 与 QJsonValue
【发布时间】:2014-07-12 01:59:15
【问题描述】:

在Qt的JSON实现中,QJsonObject类中,有两种操作符的实现(文档here):

QJsonValue QJsonObject::operator[](const QString & key) const;
QJsonValueRef QJsonObject::operator[](const QString & key);

首先,返回QJsonValueRef 与返回QJsonValue 相比有什么优势?其次,如果我只是说root['time'],其中rootQJsonObject,会返回哪个值?

【问题讨论】:

    标签: c++ qt qt5 qtcore


    【解决方案1】:

    您应该避免在提交的问题中提出多个问题。话虽如此,以下是您问题的答案:

    返回对键值的引用。

    返回值是QJsonValueRef类型,是QJsonArray和QJsonObject的帮助类。当您获得一个 QJsonValueRef 类型的对象时,您可以将其用作对 QJsonValue 的引用。如果您分配给它,则分配将应用于您从中获取引用的 QJsonArray 或 QJsonObject 中的元素。

    这意味着,您可以在返回值上调用方法,而无需在代码中显式创建临时对象,就像引用在 C++ 中的工作方式一样。

    至于第二个子问题,这取决于根对象是什么。如果它是一个 const 对象,则不能调用第二个非 const 版本,因为这会违反 const 正确性。注意这里最后的 const:

    > QJsonValue QJsonObject::operator[](const QString & key) const;
                                                              ^^^^^
    

    对于一个可变的,又名。非常量对象,您可以同时调用两者,但默认情况下会调用第二个版本。但是,通过一些 const 转换,这可以改变。

    【讨论】:

    • 只是为了检查一下,const 铸件会绕过root,对吧?类似于((const)root)['time']
    • @saiarcot895: c++ 有专门的 const cast。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2021-12-30
    • 2019-11-26
    • 2016-05-14
    • 1970-01-01
    相关资源
    最近更新 更多