问题
I have hard time understanding the explanation from stroustrup for what difficulties one must have faced, if operator overloading for '.' was allowed.
See this quote from Bjarne Stroustrup:
Operator . (dot) could in principle be overloaded using the same technique as used for ->. However, doing so can lead to questions about whether an operation is meant for the object overloading . or an object referred to by . For example:
class Y {
public:
void f();
// ...
};
class X { // assume that you can overload .
Y* p;
Y& operator.() { return *p; }
void f();
// ...
};
void g(X& x)
{
x.f(); // X::f or Y::f or error?
}
In the above example why should there be any confusion while executing x.f()
?
Y& operator.() { return *p; }
Here is what i think:
- operator.() is called on x hence isnt it obivous and intuitive that
Y& operator.()( return *p; }
should be called ? - Upon returning
*p
which points to object of type Y and henceY::f()
should be called finally ( notX::f()
)
What am i missing in stroustup's explanation? Why is it not straightforward?
回答1:
There has been some progress: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf . Due to some technical problems this won't be in C++17, but I hope to see it for C++20.
来源:https://stackoverflow.com/questions/42183631/inability-to-overload-dot-operator-in-c