调用常量引用内部的函数



嗨,我正试图在我的类中有一个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对象具有与成员函数"不兼容的类型限定符;对象::getVal">

您需要将getVal()声明为const:

inline int getVal() const { return val; }

而不是:

inline int getVal() { return val; }

foo.getConstRef()[0]返回const A &,但getVal未标记为const

还要注意,inline在这里是无用的,因为类主体中定义(而不是声明(的函数是隐式inline

最新更新