【发布时间】:2020-03-07 16:56:57
【问题描述】:
我有一个 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++ 编译代码时在 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 对象声明为常量。如果有人可以帮助我,那就太好了。谢谢!
【问题讨论】:
-
更改为
string getName() const { return id; } -
@M.M,最好返回
const string&而不是string,这样可以在不依赖编译器的情况下进行更好的优化。 -
@iammilind 不同意,因为这会引入悬空引用。它可能会返回一个
string_view -
@M.M,
string_view似乎适用于 C++17 或更高版本。我无法通过 const 参考看到任何问题。这会很有帮助,您是否应该提供一个演示“悬空引用”问题的代码示例? -
@iammilind see here
标签: c++ dictionary c++11 vector stdmap