SagiLow SagiLow - 5 months ago 64
C++ Question

C++ using square brackets with pointer to instance

I've created a singleton class which uses

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
in order to use the
[] operator
I've tried :

class risc { // singleton
unsigned long registers[8];
static risc* _instance;
risc() {
for (int i=0;i<8;i++) {
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();

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

Thanks !

Answer Source

Try this:


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) = ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download