将 boost::shared_ptr 与重载下标运算符 ([]) 的类一起使用

Using boost::shared_ptr with classes that overload the subscript operator ([])

本文关键字:一起 运算符 shared boost ptr 下标 重载      更新时间:2023-10-16

我有一个重载下标运算符的类:

class SomeClass
{
public:
   int& operator[] (const int idx)
   {
      return someArray[idx];
   }  
private:
   int someArray[10];
};

这当然允许我访问 someArray 成员的数组元素,如下所示:

SomeClass c;
int x = c[0];

但是,SomeClass 的某些实例将被包装在提升共享指针中:

boost::shared_ptr<SomeClass> p(new SomeClass);
但是,为了使用下标运算符,

我必须使用更详细的语法,以破坏下标运算符重载的简洁性:

int x = p->operator[](0);

对于这种情况,有没有办法以更简略的方式访问下标运算符?

juanchopanza和DyP都充分回答了我的问题。在谷歌搜索了评论中找到答案的礼仪后,建议发布一个自我答案,引用评论中的正确答案以关闭问题(不过,我必须等待 2 天才能接受我自己的答案)。

胡安乔潘扎的回答如下:

int x = (*p)[0];

DyP的回答如下:

SomeClass& obj = *p;
int x = obj[0];

谢谢你们的贡献。