【问题标题】:Using boost::shared_ptr with classes that overload the subscript operator ([])将 boost::shared_ptr 与重载下标运算符 ([]) 的类一起使用
【发布时间】:2013-11-29 21:11:17
【问题描述】:

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

class SomeClass
{
public:

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

private:

   int someArray[10];
};

这当然允许我像这样访问 someArray 成员的数组元素:

SomeClass c;
int x = c[0];

但是,SomeClass 的某些实例将被包裹在 boost 共享指针中:

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

但是,为了使用下标运算符,我必须使用更冗长的语法,这会破坏下标运算符重载的简洁性:

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

对于这种情况,有什么方法可以以更简写的方式访问下标运算符?

【问题讨论】:

  • (*p)[0] 怎么样?它不是很好,但它更短。
  • 您可以绑定对存储对象的引用:SomeClass&amp; obj = *p; int x = obj[0];
  • @juanchopanza 我的小学生错误,我之前尝试了您的解决方案,但取消了括号外的指针,因此我得到了编译错误。感谢您让我重回正轨。
  • @DyP 谢谢,我没想到。我可以看到这对大型代码块很有用。

标签: c++ boost shared-ptr operator-keyword subscript


【解决方案1】:

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

juanchopanza 的回答如下:

int x = (*p)[0];

DyP的回答如下:

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

感谢两位的贡献。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-19
    • 2018-05-13
    • 2018-02-19
    • 1970-01-01
    • 2017-10-12
    • 2016-11-14
    • 1970-01-01
    • 2014-04-19
    相关资源
    最近更新 更多