Guidelines for Providing Overloaded Operators


The most important guideline is: Overloaded operators must make intuitive sense for a class. For instance, if you have a String class, using + to concatenate the Strings is pretty intuitive. You might get some agreement that - , as in s2
- s1, would mean “look for s1 within s2, and if you find it, remove it.” But what could the * operator mean when applied to two Strings? There’s no obvious meaning, and you’re only going to confuse people if you provide it. So make sure that the operators you provide for your types are the ones that people expect to find.

The second guideline is: Operator usage must be consistent. In other words, if you overload ==, make sure you overload != as well. The same goes for < and >, ++ and --, and so on.

Note

The C# compiler enforces consistent overloading, and it won’t let you overload one of a pair of operators without also implementing the other. In C++, however, it is up to you to be consistent.

The third guideline is: Don’t overload obscure operators or ones that change the semantics of the language. Operators such as the comma are obscure, and few people know how they work, so it isn’t a good idea to overload them. Other operators, such as the logical AND and OR operators (&& and ||), can cause problems. In earlier chapters, you learned about the if statement and how expressions joined by && and || are only evaluated if necessary. As a result, some expressions in an if statement might never be evaluated. If you overload the AND and OR operators, the whole of the expression will have to be evaluated, which changes the way the if works.




Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
EAN: N/A
Year: 2003
Pages: 208

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net