假设我有这样一种情况:
class A {
private:
std::vector<X> _v;
// ...
public:
A();
// ...
};
并假设我需要限制对 vector 元素的访问以进行编辑和/或阅读。我应该使用什么类型的索引(int
、long
、std::size_t
、自定义迭代器或其他)来指定 vector 中的元素来自 A 类之外?
以下索引是否正确?
class A {
// ...
X getVectorElement(std::size_t);
void editSomeElementValue(std::size_t, double); // double is the type of the value to edit
};
我还有哪些其他选择?
最佳答案
您还可以使用 size_type
作为索引 - 与您的 vector 类型相同:
// Make your own type for the index based on the vector's index type
typedef std::vector<X>::size_type size_type;
// Use your typedef in the declaration of your getter
X getVectorElement(size_type index);
返回拷贝是个好主意——事实上,如果您想对调用者隐藏 vector ,这是最好的做法。返回指针或引用可能性能更高,但在 X
可变的情况下,它会为您的类打开后门操作。如果在返回引用后修改 vector ,也会产生问题,因为更改 vector 会使对其元素的引用无效。
您可以提供单独的函数来操作 X
的属性,但您也可以提供一个 setter,让用户替换您的 vector 元素。
关于c++ - 我应该如何从课外索引私有(private) vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18173301/