奇怪的const正确性错误

Meg*_*ron 2 c++

我有一个包含类的头文件.在那个类中,我有一个像这样的函数:

class Definition
{
public:
   int GetID()
   {
    return Id;
   }

//Other methods/variables
private:
   int Id;

}
Run Code Online (Sandbox Code Playgroud)

当我尝试获取该ID时:

for (std::map<Definition, std::vector<bool> >::iterator mapit = DefUseMap.begin(); mapit != DefUseMap.end(); ++mapit, defIndex++)
{
    stream << "Definition " << (*mapit).first.GetID() << " Def Use" << endl << "\t";
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

CFG.cc:1145:错误:将'const Definition'作为'int Definition :: GetID()'的'this'参数传递,丢弃限定符

是因为我在地图中使用了定义,而且我不允许在该映射定义上调用方法?有没有办法让ID变量出来?

提前致谢

Qua*_*nic 9

声明getID()方法const:

int getId() const
{
    return Id;
}
Run Code Online (Sandbox Code Playgroud)

然后可以通过const引用调用该方法,这是operator<<()传递的内容.

  • 一般规则是声明一个方法`const`如果它只需要`const`访问该对象,即`this`可以是一个`const`指针,事情就可以了.还要注意`mutable`关键字,它表示即使在`const`方法中也可以更改类成员."可变"成员的一个示例是,如果要记录对象的上次访问时间.在这种情况下,访问时间戳将是一个"可变"成员,因此可以从`const` getter方法更新. (4认同)