c – QJsonValueRef vs. QJsonValue

在Qt的
JSON实现中,在QJsonObject类中,有两个运算符实现(文档
here):

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

首先,返回QJsonValueRef而不是返回QJsonValue,这有什么好处?第二,如果我只是说root [‘time’],其中root是QJsonObject,那么返回哪个值?

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

Returns a reference to the value for key.

The return value is of type QJsonValueRef, a helper class for QJsonArray and QJsonObject. When you get an object of type QJsonValueRef, you can use it as if it were a reference to a QJsonValue. If you assign to it, the assignment will apply to the element in the QJsonArray or QJsonObject from which you got the reference.

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

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

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

对于一个可变的,又名.非const对象,你可以调用它们,但默认情况下会调用第二个版本.但是,通过一些const转换,可以改变它.

点赞