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指针就有这样的性质。
请大家指教,感激不尽。
感谢几位的回答,这个社区真的很好,谢谢。
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
*this
is TextBlock, notTextBlock&
orconst TextBlock&
.A reference in C++ is a "constant pointer pointing to a variable", which is a special case of pointers.
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.