【问题标题】:Json::Value as private class memberJson::Value 作为私有类成员
【发布时间】:2021-09-27 13:00:08
【问题描述】:

我正在编写一个 C++ 类,用于使用 jsoncpp 库从/向 json 文件读取/写入字符串。 我的问题是,是否可以为我的班级创建一个 Json::Value 私有成员并在每次我需要读/写时使用它,而不是在每个函数中创建一个新的 Json::Value?

如果是这样,我如何在构造函数中初始化它并在每个函数中访问它?

【问题讨论】:

    标签: c++ jsoncpp


    【解决方案1】:

    Json::Value 不需要任何特殊初始化。您可以将其设为private 成员变量,并像使用任何其他成员变量一样使用它。

    这是一个示例,其中我添加了对来自/到 istream/ostream 对象和一些成员函数的支持,以演示对特定字段的访问:

    #include "json/json.h"
    
    #include <fstream>
    #include <iostream>
    
    class YourClass {
    public:
        // two public accessors:
        double getTemp() const { return json_value["Temp"].asDouble(); }
        void setTemp(double value) { json_value["Temp"] = value; }
    
    private:
        Json::Value json_value;
    
        friend std::istream& operator>>(std::istream& is, YourClass& yc) {
            return is >> yc.json_value;
        }
        friend std::ostream& operator<<(std::ostream& os, const YourClass& yc) {
            return os << yc.json_value;
        }
    };
    
    int main() {
        YourClass yc;
    
        if(std::ifstream file("some_file.json"); file) {
            file >> yc;      // read file
            std::cout << yc; // print result to screen
    
            // use public member functions
            std::cout << yc.getTemp() << '\n';
            yc.setTemp(6.12);
            std::cout << yc.getTemp() << '\n';
        }
    }
    

    编辑:我被要求解释 if 语句,它的意思是 if( init-statement ; condition )(在 C++17 中添加)与此大致相同:

    { // scope of `file`
        std::ifstream file("some_file.json");
    
        if(file) { // test that `file` is in a good state
            // ... 
        }
    } // end of scope of `file`
    

    【讨论】:

    • 谢谢,有道理!我的用例是我想例如从包含多个成员的 json 文件中读取温度。例如,它可以包含温度、湿度、风等。所以我的计划是创建公共成员函数来读取/写入这些值。例如:std::string ReadTemp() 或 void WriteTemp()。我是否可以使用 return is >> yc.json_value["Temp"] 或类似的方式访问特定成员?
    • @Linus 是的,读完文件后,您可以在所有成员函数中访问名为json_value 的成员。也许直接流式传输到某些子对象(如is &gt;&gt; yc.json_value["Temp"])不是最佳的,但它是可能的。
    • @Linus 我在演示中添加了两个访问器函数
    • 非常感谢!会尝试,显然让我的头脑变得更加复杂
    • @Linus 不客气,黑客攻击愉快!
    猜你喜欢
    • 2021-08-29
    • 2018-06-10
    • 2017-03-21
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多