运算符 [] 重载写入/读取之间的区别
Difference between Operator [] overloading write/read?
我是C++新手,因为这个问题我很抱歉,但这是一场斗争。如果有人能帮助我区分以下几行,我将不胜感激。
char& operator [](int); // write (why with reference?)
char operator [](int) const; //read (why without a reference?)
char const &operator[](int) const; // what is the difference compared to the previous line?
const char *& operator[] (const int* ); // is this also possible?
您可能想阅读运算符重载的概述。
因此,回顾一些适用的观点:
-
operator[]
始终是非静态的一元成员函数。 - 可以有多个重载,就像任何其他成员函数一样。
- 按照惯例(注意!(,非 const 限定版本返回用于修改内容的引用(该引用可能由代理类型表示,但尽量避免它(。
- 按照约定,
const
限定的重载可以返回const
引用或副本,以提供对相同元素的只读访问。- 如果元素无法动态生成,请使用
const
-reference,尤其是在复制它不是简单且便宜的情况下。 - 如果上述情况不成立,请使用价值回报。
- 如果元素无法动态生成,请使用
顺便说一句:你真的希望const
成员和非const
成员相似,所以非const
可以是一个简单的内联函数,通过适当的const_cast
委托给另一个。
(不要反过来做,那不是完全允许的,也不是安全的。
关于最后一行,它使用指向const int
的指针进行索引,并返回对指向const char
的指针的引用。
这是一个非常奇怪的返回值和索引,但是如果你对它有有效的用途,为什么不呢?
为了确保有一些代码的答案,以下是这些版本使用方式的一些示例:
// Q: char& operator [](int); // write (why with reference?)
// A: this is using [] to return a mutable reference to a conceptual element in my array
my_type x; // x supports operator []
x[6] = 'A'; // actually modifies the 7th element of x
-
// Q: char operator [](int) const; //read (why without a reference?)
// A: this will return a COPY of the element at [i].
// for a char this is irrelevant, a copy is trivial
// if it was some large object you might want to return
// a const& instead and avoid the copy
char my_copy = x[6];
x[6] = 'B'; // from above
// now my_copy is 'A' but x[6] is 'B'
-
// Q: char const &operator[](int) const; // what is the difference compared to the previous line?
// A: as mentioned, for a char not a lot of difference.
// For a large object it avoids a copy
-
// Q: const char *& operator[] (const int* ); // is this also possible?
// A: yes it's possible. Yes it's completely evil. No, don't do it.
当你重载运算符[]
像char& operator [](int)
时,它可以读/写底层char
,该由条目整数索引。
但是,在许多情况下,您需要读取const
对象的属性,然后您必须通过const
方法重载该运算符,例如 char operator [](int) const
。
第三个char const &operator[](int) const
与上面一样有用,但是当基础变量const
时。
第一行告诉您,当您修改 operator[] 返回的值时,旧值也会更改。
第二行告诉你这个算子不能修改任何变量,但你可以修改 return 的值,不要改变旧的。
第三行告诉你这个运算符不能修改任何变量或返回值。
第二行和第三行的区别在于前者可以修改返回值,后者不能修改返回值,至于最后,我也是c++的新手,所以我不知道这是什么意思。
相关文章:
- ifstream 尝试读取 9 到 13 之间的无符号字符时非常奇怪的行为
- 读取USB与操作系统、C++之间传输的数据
- 为什么我的 cout 一次执行,尽管 cin 应该在两者之间读取?
- 如何读取特定单词之间的文本文件?
- 尝试从每个预期数据之间有多个空间的文件中读取和存储数据
- c++ 从大型数组中读取 3D 坐标并计算它们之间的距离
- 如何从.txt文件中读取多个2D数组,而无需每个之间的新线
- 嵌入式串行读取操作和桌面PC之间可能有什么区别
- 将文件读取为缓冲区,并避免在读取之间分裂线
- 在C++中,如何在并发读取和锁定的单线程写入uncodered_map之间进行交替
- 数据类型类和读取器/解析器之间的耦合
- 在使用pthread_create创建的线程之间读取和写入管道时,是否需要关闭 fds
- 使用 WinAPI/C++ 在 Windows 上的进程之间进行多读取器、单写入器同步锁定
- 运算符 [] 重载写入/读取之间的区别
- 在 TheADS 中的向量读取之间插入元素
- 在编译器之间读取和写入原始对象到磁盘(istream)
- 在线程之间发送和读取字符串
- C程序读取两个字符串之间的数据
- 需要读取文本文件中某些字符之间的文本
- 实现有界缓冲区(读取器和写入器之间无块,读取器之间有块,写入器之间有块)