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

'this' argument to member function has type 'const', but my function is not actually 'const'

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

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

//Accessors
string getName(){
    return id;
}

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

的地图

map<BaseStation, vector<string> > connection_map;

connection_map在while循环中更新如下,然后为了我自己的调试目的我想转储地图的内容。我将一个 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;
}

这是我尝试通过 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: ";

并且在 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

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

std::map 将密钥存储为 const

value_type std::pair<const Key, T>

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

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