FAQ 23.01 Are overloaded operators like normal functions?

Yes, overloaded operators are syntactic sugar for normal functions.

Operator overloading allows existing C++ operators to be redefined so that they work on objects of user defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the language (but they can improve understandability and reduce maintenance costs).

For example, consider the class Number that supports the member functions add() and mul(). Using named functions (that is, add() and mul()) makes sample() unnecessarily difficult to read, write, and maintain.

 #include <stdexcept> using namespace std; class Number { public:   friend Number add(Number a, Number b) throw(range_error);   friend Number mul(Number a, Number b) throw(range_error); }; Number sample(Number a, Number b, Number c) throw(range_error) { return add(add(mul(a,b), mul(b,c)), mul(c,a)); } 

The syntax is clearer if operators + and * work for class Number in the same way they work for the built-in numeric types.

 inline Number operator+ (Number a, Number b) throw(range_error) { return add(a, b); } inline Number operator* (Number a, Number b) throw(range_error) { return mul(a, b); } Number sample2(Number a, Number b, Number c) throw(range_error) { return a*b + b*c + c*a; } 


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