运算符 [] 重载写入/读取之间的区别

Difference between Operator [] overloading write/read?

本文关键字:读取 之间 区别 重载 运算符      更新时间:2023-10-16

我是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++的新手,所以我不知道这是什么意思。