代码之家  ›  专栏  ›  技术社区  ›  WhatABeautifulWorld

常量访问和非常量访问

  •  0
  • WhatABeautifulWorld  · 技术社区  · 7 年前

    我有一个内部拥有foo向量的类

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

    现在我要设计这个向量的公共访问。我在想两个版本的函数:

    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,已更新

    1 回复  |  直到 7 年前
        1
  •  1
  •   John Zwinck    7 年前

    在C++中有const和unconst访问器都有点常见。没有语言特性可以将这两种代码结合起来——您确实需要编写两次。

    顺便说一下,你不需要自己做边界检查,你可以使用 foos_.at(index) 而不是 foos_[index] 然后你会有自动边界检查。

    推荐文章