在 const 引用内调用函数
您好,我正在尝试在我的类中添加一个 getter,它返回对对象向量的“只读”引用。每个对象都有自己的变量和函数,我需要调用它们。我尝试设置它的方法是让主类中的 getter 返回一个 const 引用。但是,我似乎无法访问向量中保存的对象的值。有更好的方法吗?这是一个最小的可重现示例。谢谢。
#include <vector>
class Obj
{
private:
int val;
public:
Obj() { val = 10; }
inline int getVal() { return val; }
};
class Foo
{
private:
std::vector<Obj> obsVec;
public:
Foo()
{
Obj a;
Obj b;
obsVec.push_back(a);
obsVec.push_back(b);
}
const std::vector<Obj>& getConstRef() const { return obsVec; }
};
int main()
{
Foo foo;
foo.getConstRef()[0].getVal(); // Here is where I get the error
return 0;
}
我得到的错误是:
错误(活动)E1086 对象具有与成员函数“Obj::getVal”不兼容的类型限定符
Hi I am trying to have a getter in my class that returns a "read-only" reference to a vector of objects. Each of those objects its own variables and functions, that I need to call. The way that I am trying to set this up is to have the getter in the main class return a const reference. However, I don't seem to be able to access the values of the objects held in the vector. Is there a better way to do this? Here is a smallest reproducible example. Thank you.
#include <vector>
class Obj
{
private:
int val;
public:
Obj() { val = 10; }
inline int getVal() { return val; }
};
class Foo
{
private:
std::vector<Obj> obsVec;
public:
Foo()
{
Obj a;
Obj b;
obsVec.push_back(a);
obsVec.push_back(b);
}
const std::vector<Obj>& getConstRef() const { return obsVec; }
};
int main()
{
Foo foo;
foo.getConstRef()[0].getVal(); // Here is where I get the error
return 0;
}
The error that I get is:
Error (active) E1086 the object has type qualifiers that are not compatible with the member function "Obj::getVal"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将
getVal()
声明为 const:而不是:
You need to declare
getVal()
as const:instead of:
foo.getConstRef()[0]
返回const A &
,但getVal
未标记为const
。另请注意,
内联
在这里没有用处,因为在类主体中定义(而不是声明)的函数是隐式内联
的。foo.getConstRef()[0]
returnsconst A &
, butgetVal
is not markedconst
.Also note that
inline
is useless here, since functions defined (rather than declared) in class body are implicitlyinline
.