我有2个类别:InuReading
和InuTask
。看起来像这样:
InuReading header :
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 header :
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());
在 map 上设置数据后,它立即具有1个元素,但是一旦从 vector 中获取InuReading,其data属性就为空。如何获取要粘贴在 map 中的数据?
最佳答案
newReading
按值返回InuReading
,这意味着r
中的addTemperatureReading
是本地对象,与存储在任务readings
vector 中的对象没有任何关系。
您可能希望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
vector 的引用:InuReading& InuTask::newReading(String t, String l){
readings.push_back(InuReading(t, l);
return readings.back();
}
关于c++ - 为什么我的C++ map类成员中的值被删除了?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50494121/