I have a header file that contains a class. Within that class, I have a function like so:
class Definition
{
public:
int GetID()
{
return Id;
}
//Other methods/variables
private:
int Id;
}
When I attemped to get that ID as so:
for (std::map<Definition, std::vector<bool> >::iterator mapit = DefUseMap.begin(); mapit != DefUseMap.end(); ++mapit, defIndex++)
{
stream << "Definition " << (*mapit).first.GetID() << " Def Use" << endl <开发者_如何学C< "\t";
}
I get the following error
CFG.cc:1145: error: passing 'const Definition' as 'this' argument of 'int Definition::GetID()' discards qualifiers
is it because I'm using definition inside a map, and I'm not allowed to call methods on that mapped definition? Is there a way to get that ID variable out?
Thanks in advance
Declare the getID()
method const:
int getId() const
{
return Id;
}
Then the method can be called by a const reference, which is what operator<<()
is being passed.
The map<Key, Value>
stores your data internally in a std::pair<const Key, Value>
. This so that it will be hard to accidentally change the Key and destroy the ordering of the elements.
To be able to call GetID() for the const Key, the function will have to be declared const as well:
int GetID() const;
精彩评论