代码之家  ›  专栏  ›  技术社区  ›  danielschnoll

成员函数的“this”参数具有类型“const”,但我的函数实际上不是“const”[重复]

  •  1
  • danielschnoll  · 技术社区  · 5 年前

    我有一个C++ std::map 我用来存储有关连接组件的信息。这是我的代码片段 BaseStation 上课,很基础

    //Constructor
    BaseStation(string name, int x, int y){
        id = name;
        xpos = x;
        ypos = y;
    }
    
    //Accessors
    string getName(){
        return id;
    }
    

    在我的主代码中,有一个map声明为

    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++编译我的代码时,这是我在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() 函数绝对不是常数,我也不必声明 基站 对象也为常量。如果有人能帮我,那就太好了。谢谢!

    1 回复  |  直到 5 年前
        1
  •  3
  •   songyuanyao    5 年前

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

    值类型 std::pair<const Key, T>

    也就是说当你从 map (就像 ptr->first ),你会得到一个 常量 BaseStation .

    我想你应该申报 BaseStation::getName() 作为 常量 成员函数,因为它不应该执行修改。