如果我有一个 vector 作为类(class)的私有(private)成员,访问它的最佳方式是什么?例如下面这个简单的类
class MCL{
private:
std::vector my_vec;
public:
// Include constructor here and other member functions
}
访问 my_vec 的最佳方式是什么?具体来说,我想使用 getter 函数来访问它。
最佳答案
通过 const 引用返回它,或者如果你想允许更改则只通过引用返回它。
const std::vector<T> & getVector() const
{
return vector;
}
用法:
const std::vector<T> &v = myClass.getVector();
关于c++ - 在类中访问 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6210154/