例子:

std::string strJson = R"({"foo": "bar"})";
Json::Value root = strJson; // if it implement operator=(std::string&)

反而

std::string strJson = R"({"foo": "bar"})";

Json::CharReaderBuilder builder;
Json::CharReader* reader = builder.newCharReader();

Json::Value json;
std::string errors;

bool parsingSuccessful = reader->parse(
    strJson.c_str(),
    strJson.c_str() + strJson.size(),
    &json,
    &errors
);
delete reader;

我认为前者比后者更方便。

为什么不为 Json::Value 使用 operator=?


您可能会使用std::istream& operator>>(std::istream&, Value&)

Json::Value root;
std::stringstream(R"({"foo": "bar"})") >> root;

构造函数获取std::string是构建一个包含字符串值的值(因此isString()会返回true)。


也许你应该问问图书馆的作者。

“为什么不使用 operator= for Json::Value” Json::Value root = strJson;不使用operator =,而是复制构造函数。(并且 Json::value 具有构造函数string,但它与解析无关)。

@Jarod42 虽然它被称为“复制初始化”,但它实际上并不使用复制构造函数;Json::Value此语法将调用可以作为strJson参数的非显式构造函数

这个问题不是很清楚,如果你想评论别人的代码,那么你也应该链接到源代码,以便其他人可以查看上下文。