我有一个C++的std::map
,用于存储关于连通组件的信息。下面是来自我的BaseStation
类的代码片段,非常基础:
//Constructor
BaseStation(string name, int x, int y){
id = name;
xpos = x;
ypos = y;
}
//Accessors
string getName(){
return id;
}
在我的主代码中,我声明了一个名为connection_map
的映射:
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;
}
这是当我尝试通过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语句中高亮显示tooltip(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
对象声明为常量。如果有人能帮助我就太好了。谢谢!
string getName() const { return id; }
。 - M.Mconst string&
而不是string
,以便在不依赖编译器的情况下进行更好的优化。 - iammilindstring_view
似乎是 C++17 或更高版本的功能。我认为通过 const 引用返回没有任何问题。如果您能提供一个代码示例来演示“悬空引用”问题,那将非常有帮助。 - iammilindconst string& foo = bar().get_name();
这样的代码并不罕见。 - M.M