成员函数的"this"参数具有"const"类型,但我的函数实际上不是"const"

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

本文关键字:const 函数 我的 实际上 this 参数 成员 类型      更新时间:2023-10-16

我有一个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循环中更新如下,然后出于我自己的调试目的,我想转储映射的内容。我将一个基站对象附加到地图上(作为关键字(,作为值,我们有一个到基站对象的链接列表:

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(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_typestd::pair<const Key, T>

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

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