whats the purpose of a const “at()” and a non-const at()" in this code?

StackOverflow https://stackoverflow.com//questions/21047173

  •  21-12-2019
  •  | 
  •  

Domanda

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;     
}; 
È stato utile?

Soluzione

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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top