c++classpointersoperand

C++ using square brackets with pointer to instance


I've created a singleton class which uses GetInstance() method to get the instance address (pointer). Inside the class i have an array of unsigned long int which i've created the operator [] for it (direct access to the array). How can i use the pointer i got from GetInstance in order to use the [] operator ? I've tried :

class risc { // singleton
protected:
unsigned long registers[8];
static risc* _instance;
risc() {
    for (int i=0;i<8;i++) {
        registers[i]=0;};
    }
public:
unsigned long   operator   [](int i) const  {return registers[i];}; // get []
unsigned long & operator   [](int i)        {return registers[i];}; // set []
static risc* getInstance() { // constructor
        if (_instance==NULL) {
            _instance=new risc();
        }
        return _instance;
    }
};

risc* Risc=getInstance();
*Risc[X]=...

But it doesn't work ... is there a way i can use the brackets to access the array directly using the class pointer ?

Thanks !


Solution

  • Try this:

    (*Risc)[X]=...
    

    The square brackets operator takes precedence over the pointer dereference operator. It is also possible to call the operator by name, although this results in a rather clunky syntax:

    Risc->operator[](x) = ...