FAQ 23.06 What is the most important consideration for operators such as , , and ?

FAQ 23.06 What is the most important consideration for operators such as +=, +, and =?

Respect the user's intuition and expectations.

In classes that define +=, +, and =, the expressions a += b and a = a + b should generally have the same observable behavior. Similar comments can be made for the other identities of the built-in types. For example, if the class of a defines both a += operator that can be passed an int and the prefix ++ operator, then a += 1 and ++a should have the same observable behavior.

Similarly if the class of p defines a subscript operator and a + operator that can take i on the right side, and a dereference operator, then p[i] and *(p+i) should be equivalent.

One way to enforce these rules is to implement constructive binary operators using the corresponding mutative operators. This also simplifies maintenance. For example, the code below implements + using +=.

 class Fred { public:   friend Fred operator+ (const Fred& a, const Fred& b) throw();   Fred& operator+= (const Fred& b) throw(); }; Fred operator+ (const Fred& a, const Fred& b) throw() {   Fred result = a;   result += b;   return result; } 

Note that it is sometimes possible to implement operator+ more efficiently by not using operator+= and similarly for the other operators (operator-=, operator*=, and so on).



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

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