Reputation: 2144
I have the following code:
DataHandler::DataHandler(){
//just call the constructor with the default file.
DataHandler(DEFAULT_FILE);
}
DataHandler::DataHandler(const char* filename){
RefreshFromFile(filename);
}
void DataHandler::Refresh(){
RefreshFromFile(DEFAULT_FILE);
}
void DataHandler::RefreshFromFile(const char* filename){
std::string line, key, value;
std::ifstream file(filename);
if(file.is_open()){
while(std::getline(file, line)){
key = Base64Decode(line.substr(0, line.find(" ")));
value = Base64Decode(line.substr(line.find(" ")+1));
float floatValue = atof(value.c_str());
values[std::string(key)] = floatValue;
std::cout << "values[\"" << key << "\"] = " << values[key] << std::endl;
}
}
file.close();
}
float DataHandler::operator[](std::string index){
if(values.find(index) == values.end()){
fprintf(stderr, "ERROR: Value %s not found, returning 0.0 \n", index.c_str());
return 0.0f;
}else{
return values[index];
}
}
This all works neatly, and I get the following debug messages:
values["DRIVE_SPEED"] = 1
values["GRAB_WHEEL_SPEED"] = 0.2
values["GRAB_WHEEL_TURBO_SPEED"] = 0.6
If I try to get the size of the map, it returns 3.
But when I try to index anything, I get a not found message.
#include "DataHandler.hpp"
#include <iostream>
int main(int argc, const char * argv[])
{
DataHandler data;
data.Debug();
std::cout << data["DRIVE_SPEED"] << std::endl;
return 0;
}
What is wrong with my code?
Upvotes: 3
Views: 307
Reputation: 171117
DataHandler::DataHandler(){
//just call the constructor with the default file.
DataHandler(DEFAULT_FILE);
}
This code doesn't do what you think it does. It doesn't delegate the constructor call (as it would in Java, IIRR). Instead, it creates a temporary DataHandler
initialised with DEFAULT_FILE
, which is immediately destroyed again. The "correct" debug output you see comes from this temporary.
To solve this, drop the default constructor and change the single-parameter one like this:
DataHandler::DataHandler(const char* filename = DEFAULT_FILE) {
RefreshFromFile(filename);
}
Upvotes: 4