【问题标题】:C++ const iterator C2662C++ 常量迭代器 C2662
【发布时间】:2010-03-02 02:46:15
【问题描述】:

迭代有问题。我认为问题与 const 正确性有关。我假设 B::getGenerate() 应该是 const 代码才能正常工作,但我无法控制 B::getGenerate()。

非常感谢任何帮助。

提前致谢, jbu

代码如下:

int
A::getNumOptions() const
{
   int running_total = 0;

   BList::const_iterator iter = m_options.begin();

   while(iter != m_options.end())
   {
      if(iter->getGenerate()) //this is the line of the error; getGenerate() returns bool; no const in signature
      {
         running_total++;
      }
   }

   return running_total;
}

1>.\A.cpp(118) : 错误 C2662: 'B::getGenerate()' : 无法将 'this' 指针从 'const B' 转换为 'B &'

【问题讨论】:

  • 我假设实际上你确实在 while 循环内的 if 语句之后推进了 iter。

标签: c++ iterator constants


【解决方案1】:

好吧,如果getGenerate 是非常量,那么您的迭代器必须是非常量。如果是这种情况,您的 getNumOptions 也必须是非常量的。

如果getGenerate 不在您的控制之下,您将无能为力。但是,如果那个方法可能是const,请与实现该方法的人一起提出来;告诉他们应该是const

【讨论】:

  • 谢谢!呃。我明白了你的解释,并有一种感觉……我只是(无缘无故)认为我可以更好地控制我编写的方法是否为 const。
【解决方案2】:

B::getGenerate() 需要这样声明:

class B
{
   bool getGenerate() const;
};

'const' 关键字在这里很重要。这告诉编译器调用 getGenerate() 不会修改 B 的任何其他成员。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 2013-09-13
    • 2013-12-16
    相关资源
    最近更新 更多