C ++ overload: operator overload [] []

The question is whether it is possible to overload [] [].

Good under normal conditions, such as the vector <vector <int β†’, we overload the operand [].

But in those cases when if you define a special meaning for [] [], is it possible to have such an operator

+4
source share
5 answers

There is no special [] [] operator; its operator [] is applied to the result of another operator [].

You can emphasize the construction of [] [] by specifying the first statement that returns a special temporary object, which also has the [] operator.

+15
source

No, you will need to overload [] to return a value that [] itself has overloaded.

+11
source

As others have pointed out, there is no operator [][] , a [] operator applied to the results of the operator a [] . In the most general case, the first operator [] will return a proxy server that implements the operator [] . In the simplest case, a β€œproxy” can be T* , since in C ++ pointers implement the [] operator. a more general implementation can be done as follows:

 class ElementProxy { Container* myOwner; int myRowIndex; int myColumnIndex; public: ElementProxy( Container* owner, int rowIndex, int columnIndex ) : myOwner( owner ) , myRowIndex( rowIndex ) , myColumnIndex( columnIndex ) { } operator Type() const // lvalue to rvalue conversion { return myOwner->get( myRowIndex, myColumnIndex ); } void operator=( Type const& rhs ) const { myOwner->set( myRowIndex, myColumnIndex, rhs ); } }; class RowProxy { public: RowProxy( Container* owner, int rowIndex ) : myOwner( owner ) , myRowIndex( rowIndex ) { } ElementProxy operator[]( int columnIndex ) const { return ElementProxy( myOwner, myRowIndex, columnIndex ); } }; 

This is not perfect; if you are dealing with class types, it is not possible to support something line container[i][j].x , for example; we cannot overload operator. . If you need to support this, the best thing you can do is to overload operator-> on ElementProxy and require client code to use -> instead . although this is not a pointer, smart or otherwise.

+3
source

There are two operators. To do what you want, you must overload operator [], which returns a vector of objects.

+1
source

The index operator in C ++ is []. when you use syntax like this β€œobject [] []”, you call the operator [] for scubscript of the first object, and then the second operator [] on the object selected first.

Basically, you cannot overload the "[] []" operator because this operator does not exist. You must overload the index statement on the container object, and then overload it also in the internal object.

0
source

All Articles