为什么我们有单独的函数返回const和非const?

dma*_*324 1 c++ const operator-overloading

根据cplusplus.com,std::vector::operator[]有两个重载:

      reference operator[] (size_type n);
const_reference operator[] (size_type n) const;
Run Code Online (Sandbox Code Playgroud)

为什么我们需要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?
Run Code Online (Sandbox Code Playgroud)

Ser*_*eyA 5

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

const std::vector<int> a{10, 20, 30};
int y = a[0];
Run Code Online (Sandbox Code Playgroud)

另一方面,如果我们没有非const重载,则后续失败:

std::vector<int> a{10, 20, 30};
a[0] = 15;
Run Code Online (Sandbox Code Playgroud)

最后,但并非最不重要的是,这些功能都没有回归rvalue.两人都回归lvalue.

  • @ dma1324因为C++是强类型语言,而`const`是该类型的一部分.非const类型将在必要时衰减为const,但不是相反. (2认同)