Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 215
SagiLow Avatar asked Jun 17 '12 07:06

SagiLow


2 Answers

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) = ...
like image 150
juanchopanza Avatar answered Oct 21 '22 01:10

juanchopanza


You can use references:

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

You could have problems if you modified the pointer, but that should not happen in this case since it's a singleton.

See this answer for more details.

like image 32
KinGamer Avatar answered Oct 21 '22 02:10

KinGamer