在 const 引用内调用函数

发布于 2025-01-16 22:28:23 字数 771 浏览 6 评论 0原文

您好,我正在尝试在我的类中添加一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

中二柚 2025-01-23 22:28:23

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

inline int getVal() const { return val; }

而不是:

inline int getVal() { return val; }

You need to declare getVal() as const:

inline int getVal() const { return val; }

instead of:

inline int getVal() { return val; }
罗罗贝儿 2025-01-23 22:28:23

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

另请注意,内联在这里没有用处,因为在类主体中定义(而不是声明)的函数是隐式内联的。

foo.getConstRef()[0] returns const A &, but getVal is not marked const.

Also note that inline is useless here, since functions defined (rather than declared) in class body are implicitly inline.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文