我有一个内部拥有 foo vector 的类
class bar {
private:
vector<Foo> foos_;
}
现在我想设计对这个 vector 的公共(public)访问。我正在考虑该函数的两个版本:
Foo& getFoo(int index) {
// first do size checking, return ref
return foos[index];
}
和
const Foo& getFoo(int index) const {
// first do size checking, return const reference
return foos[index];
}
这种方法有什么缺点吗?一个明显的缺点是我只复制了几乎相同的代码两次。有更好的方法吗?
-----编辑----- 第二个访问者忘记了常量,已更新
最佳答案
同时拥有 const 和非常量访问器在 C++ 中有些常见。没有语言功能可以将两者的代码结合起来——您确实需要编写两次。
顺便说一下,你不需要自己做边界检查,你可以使用 foos_.at(index)
而不是 foos_[index]
然后你'将进行自动边界检查。
关于c++ - const 访问和非常量访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53454489/