Overload bracket operators [] to get and set

前端 未结 2 1657
忘掉有多难
忘掉有多难 2020-12-13 03:43

I have the following class:

class risc { // singleton
    protected:
        static unsigned long registers[8];

    public:
        unsigned long operator [         


        
相关标签:
2条回答
  • 2020-12-13 04:06

    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];}
    };
    
    0 讨论(0)
  • 2020-12-13 04:16

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

    0 讨论(0)
提交回复
热议问题