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

3

我有一个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对象声明为常量。如果有人能帮助我就太好了。谢谢!


4
更改为 string getName() const { return id; } - M.M
@M.M,最好返回const string&而不是string,以便在不依赖编译器的情况下进行更好的优化。 - iammilind
@M.M,string_view 似乎是 C++17 或更高版本的功能。我认为通过 const 引用返回没有任何问题。如果您能提供一个代码示例来演示“悬空引用”问题,那将非常有帮助。 - iammilind
@M.M,这不是一个真实世界的问题。没有理智的程序员会在同一个函数中删除指针/引用。是的,这是一个编码问题,但当指针被返回时也可能发生。 - iammilind
@iammilind 写类似 const string& foo = bar().get_name(); 这样的代码并不罕见。 - M.M
显示剩余2条评论
1个回答

5

std::map将键值存储为const

value_type std::pair<const Key,T>

这意味着当你从map中获取键(如ptr->first)时,你将得到一个constBaseStation

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接