我一直在try 使用boost::json::object
来存储具有多个值的JSON对象,然后根据需要修改值,但一直无法找到执行修改的方法,即使在查看了有关C++引用和重载方法的信息后也是如此,只是返回类型不同,这似乎是相关的.
在下面的测试代码中,我在boost::json::object
中创建了一个简短的JSON对象,如"Quick Look" section of the Boost.JSON documentation所示,从其中读出并显示一个值,try 修改该值,然后读出并显示新值.
#include <iostream>
#include <boost/json/src.hpp>
#include <boost/json/object.hpp>
using std::cout;
using std::endl;
int main(int argc, char* argv[]) {
boost::json::object testobj;
testobj["properties"] = { { "timestamp", "Fri Jan 6 02:17:29 PM EST 2023"}, { "textDescription", "This is a Description"} };
const boost::json::string& s = testobj.at("properties").at("textDescription").as_string();
cout << s << endl;
testobj.at("properties").at("textDescription").as_string() = "Hello, World!"; // ERROR
boost::json::string t = testobj.at("properties").at("textDescription").as_string();
cout << t << endl;
return 0;
}
在标记的错误行,会生成以下错误.
error: passing ‘const boost::json::string’ as ‘this’ argument discards qualifiers [-fpermissive]
testobj.at("properties").at("textDescription").as_string() = "Hello, World!";
^~~~~~~~~~~~~~~
根据the documentation for value::as_string,有两个重载的as_string()
方法,一个返回string&
,另一个返回string const&
.大概,返回的string&
将允许修改该值,但我不知道如何访问该方法的特定重载.我的理解是,如果实例化的类是常量,那么将使用常量重载,否则将使用非常量重载,但我的实例化是非常量的,但它不起作用.谁能指出我在这里做错了什么,或者提供一些关于修改boost::json::object
中类似值的其他方法的指导?
请注意,我还try 获取一个非常数boost::json::string& s
引用并为其分配一个新字符串,但编译器也抱怨过这一点.否则,如果将第return 0
行之前的三行注释掉,则上面代码中的其他所有内容都会按预期工作,所以问题就出在错误行.