C ++使用带方括号的指针指向实例 [英] C++ using square brackets with pointer to instance

查看:160
本文介绍了C ++使用带方括号的指针指向实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个单例类,它使用 GetInstance()方法来获取实例地址(指针)。
在类中我有一个unsigned long int数组,我创建了 operator [] (直接访问数组)。
我如何使用从 GetInstance 获得的指针以使用 []运算符
我尝试过:

  class risc {// singleton 
protected:
unsigned长寄存器[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] = ...


h2_lin>解决方案

试试这个:

  

方括号运算符优先于指针解引用运算符。也可以通过名称调用操作符,虽然这会导致一个相当拙劣的语法:

  Risc-> ](x)= ... 


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 !

解决方案

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

这篇关于C ++使用带方括号的指针指向实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆