简体   繁体   English

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

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

I have a class that overloads the subscript operator: 我有一个重载下标运算符的类:

class SomeClass
{
public:

   int& operator[] (const int idx)
   {
      return someArray[idx];
   }  

private:

   int someArray[10];
};

This of course allows me to access the array elements of the someArray member like so: 这当然允许我像这样访问someArray成员的数组元素:

SomeClass c;
int x = c[0];

However, some instances of SomeClass will be wrapped in a boost shared pointer: 但是,SomeClass的某些实例将包含在boost共享指针中:

boost::shared_ptr<SomeClass> p(new SomeClass);

However, in order to use the subscript operator I have to use a more verbose syntax that kind of defeats the succinctness of the subscript operator overload: 但是,为了使用下标运算符,我必须使用更详细的语法,这种语法会破坏下标运算符重载的简洁性:

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

Is there any way to access the subscript operator in a more shorthand manner for such instances? 有没有办法以更简单的方式访问下标运算符?

Both juanchopanzaand DyP have answered my question sufficiently. juanchopanza和DyP都充分回答了我的问题。 After googling regarding the etiquette for answers found in comments, it was suggested to post a self-answer referencing the correct answers in the comments in order to close the question (I have to wait 2 days to accept my own answer, though). 在谷歌搜索关于礼仪中的评论中找到的答案之后,有人建议在评论中发表引用正确答案的自我答案以便结束问题(我必须等待2天才能接受我自己的答案)。

juanchopanza's answer is as follows: juanchopanza的答案如下:

int x = (*p)[0];

DyP's answer is as follows: DyP的答案如下:

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

Thank you both for your contributions. 谢谢你们的贡献。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM