强制某些经营者成为会员的理由
C++ 中有 4 个运算符可以重载,但不能作为独立(又称非成员、独立)函数重载。这些运算符是:
operator =
operator ()
operator ->
operator []
这个线程很好地解释了禁止 operator =
成为非成员函数的理由。对其他三个有什么想法吗?
There are 4 operators in C++ which can be overloaded but cannot be overloaded as freestanding (aka nonmember, standalone) functions. These operators are:
operator =
operator ()
operator ->
operator []
This thread explains perfectly well the rationale behind prohibiting operator =
to be a nonmember function. Any ideas about the other three?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
原始帖子中提到的四个运算符
=
、()
、->
和[]
必须实际上可以实现为非静态成员函数(分别由 C++98 §13.5.3/1、§13.5.4/1、§13.5.5/1 和 §13.5.6/1 实现)。正如我在之前关于该主题的辩论中所记得的那样,Bjarne Stroustrup 的基本原理是保持语言的一些理智,即至少有一些你可以依赖的东西,无论其他人通过为现有的定义非成员运算符搞砸了多少事情。类。
我不确定我是否完全同意该限制是否真的有帮助,但是。
编辑:我就此咨询了 Bjarne Stroustrup(他总是乐于助人),但看起来规则的明显不一致只不过是一个冻结的历史事故。他指出,“现在看起来比那时更糟糕,因为自从制定重载规则以来,我们的左值和引用规则已经发生了变化。几年前我试图再次研究这个问题,但在生成一个之前没有时间了。完整的提案。”
干杯& hth.,
PS:《C++的设计与演进》这本书非常适合这类问题,但不幸的是我没有。
The four operators mentioned in the original posting,
=
,()
,->
and[]
, must indeed be implemented as non-static member functions (by respectively C++98 §13.5.3/1, §13.5.4/1, §13.5.5/1 and §13.5.6/1).Bjarne Stroustrup's rationale was, as I recall from earlier debates on the subject, to retain some sanity in the language, i.e. having at least some things you could rely on no matter how much Someone Else has screwed up by defining non-member operators for existing classes.
I'm not sure I completely agree that the restriction really helps with that, but.
EDIT: I consulted Bjarne Stroustrup about this (he's always helpful) but it appears that the apparent inconsistencies of the rules are no more than a case of frozen historical accident. He notes that "It looks worse now than it was then because our rules for lvalues and references have changed since the overloading rules were formulated. I tried to look into this issue again a couple of years ago, but ran out of time before producing a complete proposal."
Cheers & hth.,
PS: "The Design and Evolution of C++" book is great for this kind of question, but unfortunately I don't have it.
comp.std.c++ 上的线程讨论了的问题。
委员会成员弗朗西斯·格拉斯博罗 (Francis Glassborow) 表示:
尽量避免出现以下情况:
This thread on comp.std.c++ discusses the question.
Francis Glassborow, who was on the committee, stated:
Trying to avoid the situation where: