简体   繁体   English

奇怪的const正确性错误

[英]strange const correctness error

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: 当我尝试获取该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";
}

I get the following error 我收到以下错误

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

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? 有没有办法让ID变量出来?

Thanks in advance 提前致谢

Declare the getID() method const: 声明getID()方法const:

int getId() const
{
    return Id;
}

Then the method can be called by a const reference, which is what operator<<() is being passed. 然后可以通过const引用调用该方法,这是传递operator<<()方法。

The map<Key, Value> stores your data internally in a std::pair<const Key, Value> . map<Key, Value>将您的数据内部存储在std::pair<const Key, Value> This so that it will be hard to accidentally change the Key and destroy the ordering of the elements. 这样就很难意外地改变Key并破坏元素的排序。

To be able to call GetID() for the const Key, the function will have to be declared const as well: 为了能够为const键调用GetID(),该函数也必须被声明为const:

int GetID() const;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM