【发布时间】:2016-12-07 20:25:17
【问题描述】:
根据cplusplus.com,std::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& getInt() const,那么a.getInt() = 5不是非法的吗?另一方面,如果它返回一个非常量引用,那不合法吗?
标签: c++ operator-overloading constants