C++:重载 [ ] 运算符以进行读写访问
C++: Overloading the [ ] operator for read and write access
通常,如何声明读取和写入访问的类的索引[ ]
运算符?
我尝试了类似的东西
/**
* Read index operator.
*/
T& operator[](T u);
/**
* Write index operator
*/
const T& operator[](T u);
这给了我错误
../src/Class.h:44:14: error: 'const T& Class::operator[](T)' cannot be overloaded
../src/Class.h:39:8: error: with 'T& Class::operator[](T)'
您的可变版本很好:
T& operator[](T u);
但const
版本应该是const
成员函数,并返回const
引用:
const T& operator[](T u) const;
^^^^^
这不仅将其与其他重载区分开来,而且还允许(只读)访问类的const
实例。通常,重载成员函数可以通过其参数类型和常量/易失性限定来区分,但不能通过其返回类型来区分。
你只有一个重载,用于读取和写入:
T& operator[](int);
话虽如此,您可能还希望有一个const
重载:
const T& operator[](int) const;
这将提供对类const
实例的只读索引。
您会收到错误,因为重载函数不能仅因返回类型而异。但它们的常量可能不同。
/**
* Write index operator.
*/
T& operator[](T u);
/**
* Read index operator
*/
const T& operator[](T u) const;
注意"写入"和"读取"交换的位置。
另外,你实际上不是说运算符的参数是某种整数类型吗?
相关文章:
- Linux读,写Arduino串行
- 多线程一读一写time_t
- 将Linux打开,读,写,关闭功能以在Windows上工作
- 抛出例外:写违规访问.素数数组
- C++:重载 [ ] 运算符以进行读写访问
- 如果从其他线程访问(读/写)src缓冲区,是否有可能从memcpy获得访问冲突
- 如何使用std::lock_guard锁定对std::map的读写访问
- 单读多写器,带pthreads和锁,不带boost
- 如何从更基本的同步原语中创建多读/单写锁
- 如何使用 Windows API 正确检查对文件的有效读/写访问
- 对共享数据的线程安全访问 - 读/写实际发生,不会发生重新排序
- Q_PROPERTY参数化读写访问器
- 提升内存映射文件:读写访问
- 为银行项目计算读入/写出的问题
- 重构来自/到一个数据成员的读写访问器
- Linux下c++中的串口.可以读和写串行端口同时发生
- 在Windows+VisualC上是volatile读和写的原子
- GCC可以使用读-修改-写指令来更新易失性变量吗?
- 读(和写)Office文档自定义属性而不需要自动化
- vector多线程同步,一个读一个写:只在调整大小时锁定