std :: map不存储任何值

时间:2014-03-18 15:18:58

标签: c++ stdmap

我有以下代码:

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];
    }
}

这一切都很巧妙,我得到以下调试信息:

values["DRIVE_SPEED"] = 1
values["GRAB_WHEEL_SPEED"] = 0.2
values["GRAB_WHEEL_TURBO_SPEED"] = 0.6

如果我尝试获取地图的大小,则返回3.

但是当我尝试索引任何内容时,我收到一条未找到的消息。

#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;
}

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:3)

DataHandler::DataHandler(){
    //just call the constructor with the default file.
    DataHandler(DEFAULT_FILE);
}

此代码不会按照您的想法执行操作。它没有委托构造函数调用(就像在Java,IIRR中那样)。相反,它会创建一个用DataHandler初始化的临时DEFAULT_FILE,它会立即再次销毁。 &#34;正确&#34;您看到的调试输出来自此临时。

要解决此问题,请删除默认构造函数并更改单参数,如下所示:

DataHandler::DataHandler(const char* filename = DEFAULT_FILE) {
    RefreshFromFile(filename);
}