Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
320 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...