【发布时间】: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& obj = *p; int x = obj[0];。 -
@juanchopanza 我的小学生错误,我之前尝试了您的解决方案,但取消了括号外的指针,因此我得到了编译错误。感谢您让我重回正轨。
-
@DyP 谢谢,我没想到。我可以看到这对大型代码块很有用。
标签: c++ boost shared-ptr operator-keyword subscript