Inability to overload Dot '.' operator in c++

匿名 (未验证) 提交于 2019-12-03 00:50:01

问题:

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:

  1. operator.() is called on x hence isnt it obivous and intuitive that Y& operator.()( return *p; } should be called ?
  2. Upon returning *p which points to object of type Y and hence Y::f() should be called finally ( not X::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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!