C++ using square brackets with pointer to instance
Asked Answered
O

2

20

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 !

Olio answered 17/6, 2012 at 7:36 Comment(1)
Why do you want a pointer? static risc& getInstance() works just as well.Stonedead
A
44

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) = ...
Anteversion answered 17/6, 2012 at 7:39 Comment(1)
+1 for second tip, explicit form. You should say that works whit "this" keyword too.Becnel
B
1

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.

Bohol answered 20/9, 2017 at 18:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.