访问类中的向量 [英] Accessing vector in class

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

问题描述

如果我有一个向量作为我的类中的私人成员,什么是最好的方式访问它?例如,取以下简单类

If I have a vector as a private member in my class, what's the best way to access it? For example, take the following simple class

class MCL{
    private:
    std::vector my_vec;

    public:
    // Include constructor here and other member functions
}

访问my_vec的最佳方法是什么?具体来说,我想使用getter函数来访问它。

What's the best way to access my_vec? Specifically, I would like to use a getter function to access it.

推荐答案

通过const引用返回它,您要允许更改。

return it by const reference, or just by reference if you want to allow changing.

const std::vector<T> & getVector() const
{
    return vector;
}

用法:

const std::vector<T> &v = myClass.getVector();

这篇关于访问类中的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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