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)
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.