返回向量成员变量的引用 [英] Return reference to a vector member variable

查看:236
本文介绍了返回向量成员变量的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量作为类的成员,我想通过一个getVector()函数返回一个引用,以便以后能够修改它。是不是更好的实现函数getVector()是const?但是我在下面的代码中有一个错误限定符删除绑定引用类型...。应该修改什么?

I have a vector as member in a class and I want to return a reference to it through a getVector() function, so as to be able to modify it later. Isn’t it better practice the function getVector() to be const? However I got an error "qualifiers dropped in binding reference of type…" in the following code. What should be modified?

class VectorHolder
{
public:
VectorHolder(const std::vector<int>&);
std::vector<int>& getVector() const;

private:
std::vector<int> myVector;

};

std::vector<int> &VectorHolder::getVector() const
{
return myVector;
}


推荐答案

c $ c> const 成员函数,返回类型不能是非const引用。让它 const

Since it is a const member function, the return type cannot be non-const reference. Make it const:

const std::vector<int> &VectorHolder::getVector() const
{
   return myVector;
}

现在没关系。

为什么很好?因为在 const 成员函数中,每个成员变成 const ,这样就不能被修改,这意味着 myVector 是函数中的一个 const 向量,这就是为什么你必须使返回类型 const

Why is it fine? Because in a const member function, the every member becomes const in such a way that it cannot be modified, which means myVector is a const vector in the function, that is why you have to make the return type const as well, if it returns the reference.

现在你不能修改 对象。查看您可以做什么以及无法做什么:

Now you cannot modify the same object. See what you can do and what cannot:

 std::vector<int> & a = x.getVector();       //error - at compile time!

 const std::vector<int> & a = x.getVector(); //ok
 a.push_back(10);                            //error - at compile time!

 std::vector<int>  a = x.getVector();        //ok
 a.push_back(10);                            //ok

顺便问一下,我想知道为什么你需要这样的 VectorHolder

By the way, I'm wondering why you need such VectorHolder in the first place.

这篇关于返回向量成员变量的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆