Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
pages 365-370 (function overloading) pages 502-515 (operator overloading) pages 518-524 (friends and operator<<)
Overloading
Different signatures in a common scope, declarative scopes may differ Each overloaded operator or function must have its own definition Can overload non-member functions and operators too!
Function/Operator Overloading
class A { public: A (int i) : a_(i) {} int a () {return a_;} bool operator==(const A &a); private: int a_; };
// member operator bool A::operator==(const A &a) { // note: object itself is // the first argument return a_ == a.a_; } // non-member operator bool operator< (const A &lhs, const A &rhs) { return lhs.a() < rhs.a(); }
Remember an implicit this pointer is passed to any non-static member function Member functions/operators
The object on which the call is made isnt in the argument list Member function is passed a this pointer instead
Non-member functions/operators
Both objects appear in the functions argument list No this pointer is involved
Overloading Operators
class complex { double real_, imaginary_; public: complex(double r, double i) : re(r), im(i) {} complex operator+(complex); complex operator*(complex); };
int main (int, char *[]) { complex w(1,0), x(2,2); complex y = w.operator+(x); complex z = w + x; }
if both are defined, overload resolution determines which to use (but dont do this)
a.operator++() operator++(a)
Postfix
Enumerations are user defined types so you can define operators that are overloaded for them too!
void operator++ (BinFlag& b){b=(b*2)%TOP;}
CSE 332: C++ function and operator overloading
// name is type, no return or arguments operator int () const {return val_;} private: int val_; }
Number n(4); int i = n;
CSE 332: C++ function and operator overloading
Use overloading when you want to provide related interfaces to similar abstractions
add(int&, int) vs. add(string&, const string&)
Assigned Readings
pages 370-388 (function templates, specialization) pages 744-777 (class templates) pages 801-805 (nested class templates)