|
||||
Section 13:
|
[13.1] What's the deal with operator overloading?
It allows you to provide an intuitive interface to users of your class, plus makes it possible for templates to work equally well with classes and built-in/intrinsic types. Operator overloading allows C/C++ operators to have user-defined meanings on user-defined types (classes). Overloaded operators are syntactic sugar for function calls: class Fred { public: ... }; #if 0 // Without operator overloading: Fred add(Fred const& x, Fred const& y); Fred mul(Fred const& x, Fred const& y); Fred f(Fred const& a, Fred const& b, Fred const& c) { return add(add(mul(a,b), mul(b,c)), mul(c,a)); // Yuk... } #else // With operator overloading: Fred operator+ (Fred const& x, Fred const& y); Fred operator* (Fred const& x, Fred const& y); Fred f(Fred const& a, Fred const& b, Fred const& c) { return a*b + b*c + c*a; } #endif |