【问题标题】:Why are my values in a C++ map class member wiped?为什么我在 C++ 映射类成员中的值被擦除了?
【发布时间】:2018-05-23 17:21:16
【问题描述】:

我有 2 个课程:InuReading 和 InuTask。看起来像这样:

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);

};

犬读法:

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,它的数据属性就为空。如何让数据粘贴在地图中?

【问题讨论】:

  • 如果你对成员变量采用命名约定,生活会容易得多——即任务成员的_readings

标签: c++ object arduino


【解决方案1】:

newReading 按值返回InuReading,这意味着addTemperatureReading 中的r 是一个本地对象,与存储在任务的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());
}

请注意,此更改还要求您从newReading 返回一个引用到 readings 向量:

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

【讨论】:

  • 似乎是一个很大的解决方法。难道他不能在修改r之后将push_back移动到addTemperatureReading吗?也往后推不是更有意义吗?
  • @scohe001 我在 newReading 中执行 push_back 的原因是希望避免大量复制粘贴代码,因为 addTemperatureReading 只是众多传感器读取功能之一。我尝试将newReading更改为InuReading&amp; newReading(String t, String l);,然后将定义更改为InuReading&amp; InuTask::newReading(String t, String l){,最后做了InuReading &amp;r = newReading("temperature", sensor);,但是运行时程序崩溃了。
  • @scohe001 这相当于完​​全删除newReading 函数(因为它会完全复制读数的ctor)。我不认为这是一种解决方法。对我来说,语义是合理的:“注册一个新的阅读,并允许我自定义它。”不过,我也能看出你的出处,如果你是我的审稿人,我愿意适应。
  • @Angew ahh 够公平的,我想 OP 有他的理由把它放在那里。 +1 让它在以 OP 的方式工作时工作:)
  • @user2145184 缺少一些需要的更改,我已经添加了。
猜你喜欢
  • 2014-03-08
  • 1970-01-01
  • 2016-04-21
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-06
相关资源
最近更新 更多