成员函数的“this”参数的类型为“const”,但我的函数实际上不是“const”

dan*_*oll 3 c++ dictionary vector stdmap c++11

我有一个 C++ std::map,用于存储有关连接组件的信息。这是我课堂上的代码段BaseStation,非常基础

//Constructor
BaseStation(string name, int x, int y){
    id = name;
    xpos = x;
    ypos = y;
}

//Accessors
string getName(){
    return id;
}
Run Code Online (Sandbox Code Playgroud)

在我的主代码中,我有一个地图声明为

map<BaseStation, vector<string> > connection_map;

在 while 循环中更新connection_map如下,然后为了我自己的调试目的,我想转储地图的内容。我将 BaseStation 对象附加到地图(作为键),并将 BaseStation 对象的链接列表作为值:

connection_map[BaseStation(station_name, x, y)] = list_of_links; 
list_of_links.clear();

for(auto ptr = connection_map.begin(); ptr != connection_map.end(); ++ptr){
    cout << ptr->first.getName() << " has the following list: ";
    vector<string> list = ptr->second;
    for(int i = 0; i < list.size(); i++){
        cout << list[i] << " ";
    }
    cout << endl;
}
Run Code Online (Sandbox Code Playgroud)

这是当我尝试通过 clang++ 编译代码时在 main 中遇到的错误:

server.cpp:66:11: error: 'this' argument to member function 'getName' has type
  'const BaseStation', but function is not marked const
            cout << ptr->first.getName() << " has the following list: ";
Run Code Online (Sandbox Code Playgroud)

在 VSCode 中,cout ( cout << ptr->first.getName()) 处的工具提示突出显示如下:

the object has type qualifiers that are not compatible with the member 
function "BaseStation::getName" -- object type is: const BaseStation
Run Code Online (Sandbox Code Playgroud)

我不明白发生了什么,因为该getName()函数绝对不是常量,而且我也没有将我的BaseStation对象声明为 const。如果有人能帮助我那就太好了。谢谢!

son*_*yao 5

std::map将密钥存储为const.

值类型 std::pair<const Key, T>

map这意味着当您从(如)获取密钥时ptr->first,您将获得一个const BaseStation.

我认为你应该声明BaseStation::getName()const成员函数,因为它不应该执行修改。