【问题标题】:'this' argument to member function has type 'const', but my function is not actually 'const' [duplicate]成员函数的“this”参数的类型为“const”,但我的函数实际上不是“const”[重复]
【发布时间】: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 &lt;&lt; ptr-&gt;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&amp;而不是string,这样可以在不依赖编译器的情况下进行更好的优化。
  • @iammilind 不同意,因为这会引入悬空引用。它可能会返回一个string_view
  • @M.M, string_view 似乎适用于 C++17 或更高版本。我无法通过 const 参考看到任何问题。这会很有帮助,您是否应该提供一个演示“悬空引用”问题的代码示例?
  • @iammilind see here

标签: c++ dictionary c++11 vector stdmap


【解决方案1】:

std::map 将密钥存储为const。

value_type std::pair&lt;const Key, T&gt;

这意味着当您从map(如ptr-&gt;first)获得密钥时,您将获得const BaseStation。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 2023-03-14
    • 2014-10-18
    • 2018-05-20
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多