为什么你不能超载“.” C++ 中的运算符?
能够重载 . C++ 中的运算符并返回对对象的引用。
您可以重载 operator->
和 operator*
,但不能重载 operator。
这有技术原因吗?
It would be very useful to be able to overload the . operator in C++ and return a reference to an object.
You can overload operator->
and operator*
but not operator.
Is there a technical reason for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请参阅Bjarne Stroustrup 的这句话:
See this quote from Bjarne Stroustrup:
Stroustrup 说 C++ 应该是一种可扩展的、但不是可变的语言。
点(属性访问)运算符被认为距离语言核心太近,不允许重载。
请参阅C++ 的设计和演变,第 242 页,11.5.2 智能参考部分。
这句话中的“我”是 Bjarne Stroustrup。 你没有比这更权威的了。
如果你想真正理解 C++(如“为什么会这样”),你绝对应该阅读这本书。
Stroustrup said C++ should be an extensible, but not mutable language.
The dot (attribute access) operator was seen as too close to the core of the language to allow overloading.
See The Design and Evolution of C++, page 242, section 11.5.2 Smart References.
The "I" in this quote is Bjarne Stroustrup. You cannot be more authoritative than that.
If you want to really understand C++ (as in "why is it this way"), you should absolutely read this book.
Stroustrup 对此问题有答案:
Stroustrup has an answer for this question:
很容易理解,如果你了解一下运算符函数调用的内部机制,
假设一个类复形可以有两个成员 r 代表实部, i 代表虚部。
说 Complex C1(10,20),C2(10,2) // 我们假设类中已经有一个两个参数的构造函数。
现在,如果您将 C1+C2 编写为语句,则编译器会尝试在复数上查找 + 运算符的重载版本。 现在我们假设我重载了 + 运算符,所以
C1+C2 内部翻译为 c1.operator+(c2)
现在暂时假设您可以重载 '.' 操作员。
所以现在考虑以下调用 C1.disp()//显示复杂对象的内容 现在尝试表示为内部表示
C1.operator.(------) ,创建了完全混乱的东西。 这就是为什么我们不能重载 '.' 的原因。 操作员
It is very easy to understand, if you go through the internal mechanism of operator function invocation,
Say a class complex can have two member r for real part and i for imaginary part.
Say Complex C1(10,20),C2(10,2) // we assume there is an already a two argument constructor within class.
Now if you write C1+C2 as a statement then compiler try to find the overloaded version of + operator on complex number. Now we assume that I overload + operator, so
C1+C2 internally translated as c1.operator+(c2)
Now assume for the time beings you can overload '.' operator.
so now think following call C1.disp()//display content of a complex object Now try to represent as an internal representation
C1.operator.(------) , completely messy things created. That is the reason why we can't overload '.' operator