【问题标题】:Why do we have separate functions that return const and non-const? [duplicate]为什么我们有返回 const 和 non-const 的单独函数? [复制]
【发布时间】:2016-12-07 20:25:17
【问题描述】:

根据cplusplus.comstd::vector::operator[]有两个重载:

      reference operator[] (size_type n);
const_reference operator[] (size_type n) const;

为什么我们需要const 版本的函数?或者,我们为什么不写一个非常量函数?

例如在下面的代码中:

std::vector<int> a = {1, 2, 3, 4, 5};
int b = a[1] + a[3];  // Why does it matter if this is const?

【问题讨论】:

  • 不,它们都返回左值...
  • @Brian 如果你有一个类a 和函数const int&amp; getInt() const,那么a.getInt() = 5 不是非法的吗?另一方面,如果它返回一个非常量引用,那不合法吗?

标签: c++ operator-overloading constants


【解决方案1】:

const 重载将在对象本身被声明为const 时被调用。例如,如果我们在std::vector 上只有非常量的operator[] 重载,则以下代码将拒绝编译:

const std::vector<int> a{10, 20, 30};
int y = a[0];

另一方面,如果我们没有非常量重载,以下操作将失败:

std::vector<int> a{10, 20, 30};
a[0] = 15;

最后但并非最不重要的一点是,这些函数都没有返回rvalue。两者都返回lvalue

【讨论】:

  • 如果我在这里遗漏了一些愚蠢的东西,我很抱歉,但是为什么第一个 sn-p 不能调用非常量重载?
  • @dma1324 因为 C++ 是一种强类型语言,而const 是该类型的一部分。非 const 类型会在必要时衰减为 const 类型,但反之则不会。
【解决方案2】:

引用返回版本可以使用括号表示法修改向量:

a[1] = -1;

由于左侧的对象是对向量中条目的引用,这实际上修改了向量。

const_reference 返回版本可以访问 const 向量的元素。

const vector<int> a {1, 3};
int x = a[0];

如果没有 const_reference 重载,这将无法编译。

【讨论】:

    【解决方案3】:

    const 版本的存在是为了允许对常量向量进行元素访问(只读)。 没有它,一个常量向量将是一个WOM

    该函数返回一个 const 引用,这意味着您不能为其分配新值,但您可以将其复制到其他地方(如果它是可复制的)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      相关资源
      最近更新 更多