将 boost::shared_ptr 与重载下标运算符 ([]) 的类一起使用
Using boost::shared_ptr with classes that overload the subscript operator ([])
我有一个重载下标运算符的类:
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];
谢谢你们的贡献。
相关文章:
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 将 [][] 运算符与向量一起使用?
- 不能将重载比较运算符与 Catch 测试一起使用
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 为什么我不能将运算符+与reverse_iterator一起使用?
- 将流运算符与Template类一起使用
- 让类与运算符一起工作更简单的方法
- 将运算符<<与隐式转换的非基本数据类型一起使用时出错
- 为什么重载运算符不与 std::string 一起使用 msvc /MD 标志
- #define 与运算符一起使用
- 将赋值运算符与make_pair方法一起使用会生成 CLion 警告
- 是否可以将引用类型别名与指针运算符一起使用来声明对指针的引用?
- 返回对象如何与分配运算符一起工作
- 将逻辑 OR 与 cout 运算符一起使用
- 如何将模运算符与其他数据类型一起使用
- 为什么在 sizeof() 函数中与 * 运算符一起使用和不使用 * 运算符时,指向结构变量的指针大小会有所不同?
- 将[]运算符与链接列表一起使用
- 将赋值运算符与 unique_ptr 向量一起使用
- 我可以将 std:fixed 或 std::setprecision() 与>>运算符一起使用吗?
- 在C++中,我们如何将插入运算符和其他运算符链接在一起