C++常量迭代器 C2662
迭代时遇到问题。我认为问题与 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 &'
Having problems iterating. Problem has to do with const correctness, I think. I assume B::getGenerate() should be const for this code to work, but I don't have control over B::getGenerate().
Any help is greatly appreciated.
Thanks in advance,
jbu
Code follows:
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) : error C2662: 'B::getGenerate()' : cannot convert 'this' pointer from 'const B' to 'B &'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,如果 getGenerate 是非常量,那么您的迭代器也必须是非常量。如果是这种情况,您的 getNumOptions 也必须是非常量。
如果
getGenerate
不在您的控制之下,则您无能为力。但是,如果该方法可能const
,请与实现该方法的人一起提出;告诉他们它应该是const。Well, if
getGenerate
is non-const, your iterator must be non-const. And if that's the case, yourgetNumOptions
will also have to be non-const.If
getGenerate
isn't under you control, there isn't anything else you can do. But if that method could beconst
, bring it up with whoever implemented that method; tell them it should beconst
.B::getGenerate() 需要这样声明:
“const”关键字是这里的重要部分。这告诉编译器调用 getGenerate() 不会修改 B 的任何其他成员。
B::getGenerate() needs to be declared like this:
The 'const' keyword is the important bit here. This tells the compiler that calling getGenerate() will not modify any of the other members of B.