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

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

//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 ++编译代码时遇到的主要错误:

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 << 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。如果有人可以帮助我,那就太好了。谢谢!

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

std::map将密钥存储为const

  

value_type std::pair<const Key,T>

这意味着当您从map(如ptr->first)那里获得密钥时,您会得到const BaseStation

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

本文链接:https://www.f2er.com/3120390.html

大家都在问