lundi 11 novembre 2019

'this' argument to member function has type 'const', but my function is not actually 'const'

I have a C++ std::map that I'm using to store information about connected components. Here's the segment of code from my BaseStation class, it's very basic

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

//Accessors
string getName(){
    return id;
}

In my main code, I have a map declared as

map<BaseStation, vector<string> > connection_map;

The connection_map is updated in a while loop as follows, and then for my own debugging purposes I want to dump the contents of the map. I append a BaseStation object to the map (as the key) and as the value we have the list of links to the BaseStation object:

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;
}

This is the error I get in my main when I try to compile my code via 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: ";

and in VSCode, the tooltip highlight at the cout (cout << ptr->first.getName()) is the following:

the object has type qualifiers that are not compatible with the member 
function "BaseStation::getName" -- object type is: const BaseStation

I don't understand what's going on, as the getName() function is most definitely not constant, and nowhere do I declare my BaseStation object as const either. If someone could help me out that would be great. Thanks!

Aucun commentaire:

Enregistrer un commentaire