Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 常量访问和非常量访问_C++_Design Patterns - Fatal编程技术网

C++ 常量访问和非常量访问

C++ 常量访问和非常量访问,c++,design-patterns,C++,Design Patterns,我有一个类,它内部拥有一个foo向量 class bar { private: vector<Foo> foos_; } 及 这种方法有什么缺点吗?一个明显的缺点是我只复制了两次几乎相同的代码。有更好的方法吗 ---编辑--- 第二个访问器忘记了const,更新的既有const也有非const访问器在C++中有点常见。没有语言特性来组合这两种语言的代码,您确实需要编写两次 顺便说一句,您不需要自己进行边界检查,您可以使用foos_u2;atindex而不是foos_2;

我有一个类,它内部拥有一个foo向量

class bar {
  private:
    vector<Foo> foos_;
}

这种方法有什么缺点吗?一个明显的缺点是我只复制了两次几乎相同的代码。有更好的方法吗

---编辑---
第二个访问器忘记了const,更新的

既有const也有非const访问器在C++中有点常见。没有语言特性来组合这两种语言的代码,您确实需要编写两次


顺便说一句,您不需要自己进行边界检查,您可以使用foos_u2;atindex而不是foos_2;[index],然后您就可以进行自动边界检查。

为什么不从const方法中调用non-const函数呢?因为您不能从const方法中调用non-const方法。C++不这样工作,避免这种情况。你有一个设计缺陷。一个常见的技术是这样的:Foo&getFooint index{const bar*constThis=this;返回const\u castcontthis->getFooindex;}@tedlynmo然后std::vector也是如此。其运算符[]使用相同的方法。
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];
}