Operator []重载写入/读取之间的区别?

时间:2014-12-14 13:55:49

标签: c++ pointers reference operator-overloading

我是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?

4 个答案:

答案 0 :(得分:6)

您可能需要阅读Operator overloading的概述。

所以,回顾一些适用的观点:

  • operator[] 总是非静态一元成员函数。
  • 可能存在多个重载,例如任何其他成员函数。
  • 按照惯例(heed it!),非const限定版本返回一个用于修改内容的引用(引用可能由代理类型表示,尽管试图使用它)。
  • 按照惯例,const - 限定的重载可以返回const引用或副本,以提供对相同元素的只读访问。
    • 如果无法动态生成元素,请使用const - 引用,特别是如果要复制它并不简单且便宜。
    • 如果上述情况不成立,请使用值返回。

BTW:你真的希望const和非const成员是类似的,所以非const可以是一个简单的内联函数委托给另一个适当const_cast
(不要反过来做,这是不允许的,或者是安全的。)

关于最后一行,该索引带有指向const int的索引,并返回对指向const char的指针的引用。
这是一个非常奇怪的返回值和索引,但如果你有一个有效的用途,为什么不呢?

答案 1 :(得分:2)

当您重载[]之类的运算符char& operator [](int)时,它可以读取/写入由条目整数索引的基础char

但是,在许多情况下,您需要读取const对象的属性,然后您必须通过const方法重载该运算符,例如char operator [](int) const

第三个char const &operator[](int) const与上面相同,但是当底层变量为const时。

答案 2 :(得分:2)

第一行告诉您修改operator []返回值时,旧值也会改变。

第二行告诉你这个操作符不能修改任何变量,但你可以修改return的值而不要改变旧的。

第三行告诉你这个操作符不能修改任何变量或返回值。

第二行和第三行之间的区别是前者可以修改返回值,后者不能修改返回值,因为最后,我也是c ++的新手,所以我不知道知道这意味着什么。

答案 3 :(得分:2)

并且只是为了确保有一些代码的答案,下面是一些可能使用这些版本的例子:

// 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.
相关问题