gpt4 book ai didi

c++ - 无法在 const 成员函数内生成 'non-const for range'

转载 作者:行者123 更新时间:2023-11-30 02:22:54 24 4
gpt4 key购买 nike

在此代码中:

int main(int argc, char *argv[])
{
class Bar {
public:
int bar;
};
class Foo {
public:
std::vector<Bar> myBars;
Bar &getOneBar() const {
for( Bar &bar : myBars ) {
return bar;
}
}
};
}

我得到一个编译器错误:

error: binding ‘const main(int, char**)::Bar’ to reference of type ‘main(int, char**)::Bar&’ discards qualifiers

我接受,但不理解,因为我没有修改该函数中类的内容。我知道我可以在调用 getOneBar() 之后修改对象,但不能在内部修改。

我已经用 const_cast 解决了它,但我有点不喜欢那样。

 Bar &getOneBar() const {
for( Bar &bar : myBars ) {
return const_cast<Bar &>(bar);
}
}

最佳答案

I understand that I could modify the object after the call to getOneBar(), but not inside.

这是不允许的。更准确地说,数据成员被视为 constconst里面成员函数。那么myBars变成 const std::vector<Bar> ,从它返回的元素变为 const也;它与返回类型不匹配Bar & ,您不能将对非常量的引用绑定(bind)到 const .

如您所说,const_cast是个坏主意。更明确的方法应该是同时声明 const和非 const成员函数重载,例如

const Bar& getOneBar() const {
for (const Bar &bar : myBars) {
return bar;
}
}

Bar& getOneBar() {
for (Bar &bar : myBars) {
return bar;
}
}

关于c++ - 无法在 const 成员函数内生成 'non-const for range',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46782240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com