Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator[][] overload

Is it possible to overload [] operator twice? To allow, something like this: function[3][3](like in a two dimensional array).

If it is possible, I would like to see some example code.

like image 456
icepopo Avatar asked Aug 07 '11 00:08

icepopo


People also ask

What is meant by operator overloading?

Polymorphism: Polymorphism (or operator overloading) is a manner in which OO systems allow the same operator name or symbol to be used for multiple operations. That is, it allows the operator symbol or name to be bound to more than one implementation of the operator. A simple example of this is the “+” sign.

Why are operators overloaded?

The need for operator overloading in C++It allows us to provide an intuitive interface to our class users, plus makes it possible for templates to work equally well with classes and built-in types. Operator overloading allows C++ operators to have user-defined meanings on user-defined types or classes.

Which function overloads the operator ==?

In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading == .

What is operator overloading and why we use it?

Operator overloading is syntactic sugar, and is used because it allows programming using notation nearer to the target domain and allows user-defined types a similar level of syntactic support as types built into a language.


2 Answers

You can overload operator[] to return an object on which you can use operator[] again to get a result.

class ArrayOfArrays { public:     ArrayOfArrays() {         _arrayofarrays = new int*[10];         for(int i = 0; i < 10; ++i)             _arrayofarrays[i] = new int[10];     }      class Proxy {     public:         Proxy(int* _array) : _array(_array) { }          int operator[](int index) {             return _array[index];         }     private:         int* _array;     };      Proxy operator[](int index) {         return Proxy(_arrayofarrays[index]);     }  private:     int** _arrayofarrays; }; 

Then you can use it like:

ArrayOfArrays aoa; aoa[3][5]; 

This is just a simple example, you'd want to add a bunch of bounds checking and stuff, but you get the idea.

like image 159
Seth Carnegie Avatar answered Sep 19 '22 05:09

Seth Carnegie


For a two dimensional array, specifically, you might get away with a single operator[] overload that returns a pointer to the first element of each row.

Then you can use the built-in indexing operator to access each element within the row.

like image 45
Bo Persson Avatar answered Sep 22 '22 05:09

Bo Persson