C++ Primer, Fifth Edition:这个类的最后一行,为何返回的是地址?我一直觉得应该是return this->operator*();
才对啊。不是说p->mem
和(*p).mem
应该是一样的吗?
class StrBlobPtr
{
public:
std::string& operator*() const
{
auto p = check(curr, "dereference past end");
return (*p)[curr]; // (*p) is the vector to which this object points
}
std::string* operator->() const
{
// delegate the real work to the dereference operator
return & this->operator*();
} // other members as before
};
The dereference operator checks that curr is still in range and, if so, returns a reference to the element denoted by curr. The arrow operator avoids doing any work of its own by calling the dereference operator and returning the address of the element
returned by that operator.
Please look at the code: 3 classes are defined, C contains B, and B contains A. A, B, and C all define an action member function. Both B and C overload the arrow operator. The difference is that the overloaded arrow operator of B returns a pointer to a class A object, while the overloaded arrow operator of C returns an object of class B (that is, where your question is). ).
Output of the program:
Action in class C!
Action in class A!
1
The first output is easier to understand, so I won’t explain it. The second and third outputs are strange. Why are they like this? Let’s take a look at the official agreement description:
This explains the output of the above operation c->action();, because c-> returns type B instead of a pointer, and all programs will iteratively operate the -> overloaded function of type B, What is returned at this time is a pointer of type A, so there is no need to iterate to find the action() function of A at this time. If A does not have an action() function, an error will occur. So the actual operation of the code c->action(); is as follows: c.operator->().operator->()->action(); The third output is the same as c- >x;The actual operation is c.operator->().operator->()->x, so even if the x variable of C is private, it will not affect the program, and there will not even be a warning.
If what is returned in your program is not a pointer, then the program will iterately search for the -> operation of std::string. This operation returns the return value of the StrBlobPtr-> operation. Do you think this is your What do you hope? In other words, if a type is returned instead of a pointer -> will iterate indefinitely until a pointer is returned and then the method or member variable you specified at the beginning will be called. This is the unique difference of -> .