std::map未存储任何值

3

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

这一切都很顺利,我收到了以下调试信息:
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
operator[] 应该返回一个浮点数的引用,以使其可写,否则该方法应为 const 吗? - tgmath
不行,如果它是const的话,我不能在我的映射中存储一个浮点数。 - Dirk
@user1833511 tgmath意味着您应该将运算符成员函数设置为const,以便可以从const DataHandler对象中调用它。 - vlad_tepesch
1个回答

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

这段代码并不像你想象的那样工作。它并没有委托构造函数调用(就像Java中一样)。相反,它创建了一个临时的DataHandler,并初始化为DEFAULT_FILE,然后立即销毁。你看到的“正确”调试输出来自于这个临时对象。

要解决这个问题,需要删除默认构造函数,并将单参数构造函数更改为以下形式:

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

4
如果你使用现代的 C++ 编译器,你可能也可以委托构造函数调用,就像 https://dev59.com/BWYr5IYBdhLWcg3wFGdS 中展示的那样。 - danielschemmel
谢谢,我不知道你不能这样做。(我习惯了Objective-C) - Dirk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接