c++关于调用重在运算符的类型问题。
PHP中文网
PHP中文网 2017-04-17 15:34:53
0
3
461

effective c++中有这么一段。

class  TextBlock{
public:
    ...
    const char& operator[](std::size_t position) const
    {
    ...
    return text[position];
    }
    
    char& operator[] (std::size_t position)
    {
    ...
    }
private:
    std::string text;
    

代码大致这样,不明白的是它说:

*this 的原始类型分别是TextBlock&,和const TextBlock&。

为什呢这个this类型是引用呢?this不是直接指向类实例的么。

TextBlock a1 = TextBlock("hello");
TextBlock &a2 = a1;
a2[0]

是这样得来的引用?我不知道是我看这个书没看清楚,还是本身*this指针就有这样的性质。

请大家指教,感激不尽。

感谢几位的回答,这个社区真的很好,谢谢。

PHP中文网
PHP中文网

认证0级讲师

reply all(3)
伊谢尔伦

Clarify two points:

  • A reference is a type

  • The type of the value produced by an expression will never be a reference type

There is an error here in the book. The type of *this may be const T or T, and the value category is always an lvalue. ..is an lvalue ..lvalue . .

左手右手慢动作
    The type of
  1. *this is TextBlock, not TextBlock& or const TextBlock&.

  2. A reference in C++ is a "constant pointer pointing to a variable", which is a special case of pointers.

  3. TextBlock &a2 = a1; assigns a value to reference a2 so that it points to a1, and the a2 backdoor cannot be modified (points to other TextBlock objects).

阿神

*This is TextBLock, and reference is not a type. The purpose of this is: strong transfer will generate new objects (copy construction), so a reference must be added.

@felix021 Thanks for the advice. What I said above is indeed wrong. Reference is a type. What I actually want to express is that neither reference nor pointer can exist independently of the data type. The expression returned can never be A reference, value category can be lvalue, rvalue, etc.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template