Download presentation
Presentation is loading. Please wait.
1
Review of Function Overloading
Allows different functions to have the same name if they have different types or numbers of arguments, e.g. int sqr(int x) { return x*x; } double sqr(double x) { return x*x; } double sqr(double x, double y) { return x*y; } int i = 2; double x = 1.2, y = 2.0; cout << sqr(i) << “ ” << sqr(x) << “ “ << sqr(x,y);
2
Operator Overloading This is a powerful C++ feature that allows the use of operators for user defined classes, e.g. dVector A, B, C, D; // a user defined class C = A + B; // = and + is overloaded D = A*B; // * is overloaded (dot product) cout << D; // << is overloaded Similar to function overloading except it uses operators
3
Member Operator Functions
General form: return-type class-name::operator#(argument-list) { // operation to be performed } e.g. void dVector::operator=(dVector &v2) { // v1 = v2 int i; if ( n1 != v2.n1 || n2 != v2.n2 ) return; // error ! for ( i = n1; i <= n2; i++ ) e(i) = v2.e(i); // copy elements }
4
Improved = Operator dVector dVector::operator=(dVector &v2) { // v1 = v2 int i; dVector *ans; // declare a return variable ans = new dVector(n1,n2); // allocate a dVector if ( n1 != v2.n1 || n2 != v2.n2 ) return *ans; // error ! for ( i = n1; i <= n2; i++ ) ans->e(i) = e(i) = v2.e(i); // copy elements return *ans; }
5
Overloading the + Operator
dVector dVector::operator+(dVector &v2) { // v1 + v2 int i; dVector *ans; // declare a return variable ans = new dVector(n1,n2); // dynamically allocate if ( n1 != v2.n1 || n2 != v2.n2 ) return *ans; // error ! for ( i = n1; i <= n2; i++ ) ans->e(i) = e(i) + v2.e(i); // copy elements return *ans; }
6
Overloading Unary Operators
Example: Norm operator double dVector::operator!() { int i; double ans=0.0; // declare a return variable for ( i = n1; i <= n2; i++ ) ans += e(i)*e(i); return sqrt(ans); }
7
Friend Functions A Friend function is not a member function of a class, but it has access to all its private members, e.g. class number { double x; // private member public: number() { x = 7.11; } // constructor friend void show_x(number n); }; void show_x(number n) { cout << n.x; } number n1; show_x(n1); 7.11;
8
<< Operator Overloading
class dVector { friend ostream &operator<<(ostream &stream, dVector &v); … }; ostream &operator<<(ostream &stream, dVector &v) { // example usage: cout << v1 << v2 << v3; int i; for ( i = v.n1; i <= v.n2; i++ ) stream << "\n" << v.e(i); return stream; }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.