为什么我的C ++地图类成员中的值被擦除?

时间:2018-05-23 17:21:16

标签: c++ object arduino

我有两个课程:InuReadingInuTask。看起来像这样:

InuReading标题:

class InuReading{
    public:
        InuReading(String t, String l){
            type = t;
            label = l;
        };
        String type;
        String label;
        std::map<String, String> data;
        void set(String key, float d);
};

InuTask标题:

class InuTask{
    public:
        InuTask(String);
        String type;
        void addTemperatureReading(String sensor, float temperature);
        std::vector<InuReading> readings;
    private:
        InuReading newReading(String t, String l);

};

InuReading方法:

void InuReading::set(String key, float d){
    data[key] = String(d); 
};

InuTask方法:

InuTask::InuTask(String t){
    type = t;
}

InuReading InuTask::newReading(String t, String l){
    InuReading r(t, l);
    readings.push_back(r);
    return r;
}

void InuTask::addTemperatureReading(String sensor, float temperature){
    InuReading r = newReading("temperature", sensor);
    r.set("d", temperature);
    // Size here after setting "d" to 30.0 is 1, which is proper
    Serial.printf("Size of %s is now: %i \n", r.type.c_str(), r.data.size());
}

主:

InuTask task("Log");
task.addTemperatureReading("Temperature", 30);
// This returns 0, all data is missing now?
Serial.println(task.readings[0].data.size());

在地图上设置数据后,它立即有1个元素,但是一旦我从向量中获取InuReading,其data属性为空。如何将数据粘贴在地图中?

1 个答案:

答案 0 :(得分:3)

newReading按值返回InuReading,这意味着r中的addTemperatureReading是一个本地对象,与任务{{{}中存储的对象没有任何关系。 1}}向量。

您可能希望readings返回引用,并更改newReading以使用引用:

addTemperatureReading

请注意,此更改还要求您将引用void InuTask::addTemperatureReading(String sensor, float temperature){ InuReading &r = newReading("temperature", sensor); r.set("d", temperature); // Size here after setting "d" to 30.0 is 1, which is proper Serial.printf("Size of %s is now: %i \n", r.type.c_str(), r.data.size()); } 返回到 readings向量:

newReading