本文介绍了强制某些运算符成为成员的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++中有4个运算符可以重载,但不能作为独立的(也称为非成员,独立)函数重载。这些运算符是:

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 []

  • operator =
  • 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?

推荐答案

原始发布中提到的四个操作符 = code>(), - > [] 作为非静态成员函数(分别由C ++ 98§13.5.3/ 1,§13.5.4/ 1,§13.5.5/ 1和§13.5.6/ 1)实现。

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的理由是,我从前面关于这个问题的辩论中回忆起,保留了一些理智的语言,即至少有一些事情你可以依靠,不管有人Else已经拧

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 :我咨询了Bjarne Stroustrup(他总是很有帮助),但似乎规则的明显不一致只不过是一个冻结的历史事故的情况。他注意到现在看起来比现在更糟糕了,因为我们的规则左右和引用已经改变,因为重载规则制定。我试图在几年前再次研究这个问题,但跑出了时间之前,生产完成提案。

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."

hth。

PS:C ++的设计和进化这本书对这类问题很有用,但很遗憾,我没有这个问题。

PS: "The Design and Evolution of C++" book is great for this kind of question, but unfortunately I don't have it.

这篇关于强制某些运算符成为成员的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!