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?
where () is the function call operator and [] is the subscript operator. You cannot overload the following operators: .
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.
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.
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];} };
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With