Overload bracket operators [] to get and set

C++IndexingOverloadingSquare Bracket

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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];}
};

Solution 2 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSagiLowView Question on Stackoverflow
Solution 1 - C++Andrew DurwardView Answer on Stackoverflow
Solution 2 - C++NaveenView Answer on Stackoverflow