Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload bracket operators [] to get and set

I have the following class:

class risc { // singleton     protected:         static unsigned long registers[8];      public:         unsigned long operator [](int i)         {             return registers[i];         } }; 

as you can see I've implemented the square brackets operator for "getting".
Now I would like to implement it for setting, i.e.: risc[1] = 2.

How can it be done?

like image 787
SagiLow Avatar asked Jun 16 '12 19:06

SagiLow


People also ask

Can [] operator be overloaded?

where () is the function call operator and [] is the subscript operator. You cannot overload the following operators: .

What are square brackets used for in C++?

Square brackets are used to index (access) elements in arrays and also Strings. Specifically lost[i] will evaluate to the ith item in the array named lost.

What is an operator overloading in C++?

It's a type of polymorphism in which an operator is overloaded to give it the user-defined meaning. C++ allows us to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading, respectively.


2 Answers

Try this:

class risc { // singleton protected:     static unsigned long registers[8];  public:     unsigned long operator [](int i) const    {return registers[i];}     unsigned long & operator [](int i) {return registers[i];} }; 
like image 93
Andrew Durward Avatar answered Sep 17 '22 08:09

Andrew Durward


You need to return a reference from your operator[] so that the user of the class use it for setting the value. So the function signature would be unsigned long& operator [](int i).

like image 32
Naveen Avatar answered Sep 20 '22 08:09

Naveen