Overload bracket operators [] to get and set
Asked Answered
D

2

74

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?

Devote answered 16/6, 2012 at 19:54 Comment(1)
I came across to this because of this video which I am watching as of now - youtu.be/ux3s1IIvNdg?t=603Desdee
S
99

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];}
};
Swatow answered 16/6, 2012 at 19:57 Comment(8)
You can also return a const long&. If it weren't a native type then that way would be preferred but for types like long it's fine to return it by value.Gumma
Note that it would be a good idea to add a test on i to make sure it's a number between 0 and 7 inclusive. And when dealing with much more complex types than a long, you generally create a reference class (riscDataRef) which holds the necessary information to let you make changes to the main class.Ambivalence
Shouldn't the ints be replaced with size_t?Altazimuth
@Andrew unsigned long operator [](int i) const {return registers[i];} Will the above be called ? I see the other one being called for both getting and setting unsigned long & operator [](int i) {return registers[i];}Towline
@tanweeralam The const variant will be called when the object or reference on which it's called is const. E.g. const risc r; r[0];Swatow
@AndrewDurward I used your code and called like this risc m; m[0]=1; DEBUG_PRINT("%d",m[0]);//{I expect the const one to be called here}. Even though the answer is correct printed, in both cases only the second function is called. unsigned long & operator [](int i) {return registers[i];}Towline
@tanweeralam I've already addressed this. See my previous comment. If that doesn't help then please post a new question rather than using the comments section.Swatow
@AlexisWilke, STL containers have the at function for this purpose which checks the boundaries.Whipping
C
18

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).

Crossover answered 16/6, 2012 at 19:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.