whats the purpose of a const “at()” and a non-const at()" in this code?
题
template<typename T>
class vector {
vector();
vector(const vector& c);
vector(size_t num, const T& val = T());
~vector();
T& operator[](size_t index);
const T& operator[](size_t index) const;
vector operator=(const vector& v);
T& at(size_t loc);
const T& at(size_t loc) const;
void pop_back();
void push_back(const T& val);
size_t size() const;
};
解决方案
It allows you to look up an item when the vector is const, or non-const.
For example:
const vector<int> x;
x.at(0); // Calls const version;
vector<int> y;
x.at(0); // Calls non-const version;
It's a very common C++ paradigm to overload a method based on const
. In the example yo've posted the operator[]
also has a const and non-const version, for the same reason.
其他提示
You can say you are overloading the vector.at()
method. First one takes an implicit Vector* this
parameter, but second one takes a const Vector* this
parameter (beside the const reference return, note the const
on the method signature). As consequence, first one will be called on const instances, and the second one on non-const instances.
T& at(size_t loc);
returns a reference to T
and can work on a vector<>
which was not declared as const
. const T& at(size_t loc) const;
returns a const
reference to T
and is used when you have a vector<>
which was declared as const
.
Pretty constent, right? The container preserves the meaning of const
.