Overload Operator []

Say I have a container class called MyContainerClass that contains integers. The operator [] , as you know, can be overloaded, so that the user can more intuitively access the values, as if the container were a regular array. For instance:

 MyContainerClass MyInstance; // ... int ValueAtIndex = MyInstance[3]; // Gets the value at the index of 3. 

The obvious return type for operator[] is int , but then the user will not be able to do something like this:

 MyContainerClass MyInstance; MyInstance[3] = 5; 

So what should be the return type for operator[] ?

+4
source share
4 answers

The obvious return type is int& :)

To increase the study:

 int &operator[](ptrdiff_t i) { return myarray[i]; } int const& operator[](ptrdiff_t i) const { return myarray[i]; } // ^ could be "int" too. Doesn't matter for a simple type as "int". 
+15
source

This should be a link:

 int & 
+5
source
 class MyContainerClass { public: int& operator[](unsigned int index); int operator[](unsigned int index) const; // ... }; 

Returning the link allows the user to use the result as an lvalue, as in your example MyInstance[3] = 5; . Adding a const overload ensures that they cannot do this if MyInstance is a variable or const reference.

But sometimes you want everything to look like this, but there really isn’t an int you can reference. Or maybe you want to allow several types on the right side of MyInstance[3] = expr; . In this case, you can use a dummy object that overloads the destination:

 class MyContainerClass { private: class Index { public: Index& operator=(int val); Index& operator=(const string& val); private: Index(MyContainerClass& cont, unsigned int ind); MyContainerClass& m_cont; unsigned int m_ind; friend class MyContainerClass; }; public: Index operator[](unsigned int ind) { return Index(*this, ind); } int operator[](unsigned int ind) const; // ... }; 
+2
source

int&

link return allows you to use the return value as the left side of the job.

the same reason operator<<() returns ostream& , which allows cout << a << b;

+1
source

Source: https://habr.com/ru/post/1333058/


All Articles