Ch-3.Function + Operator Overloading
Ch-3.Function + Operator Overloading
Ch-3.Function + Operator Overloading
Function Overloading
Default Argument
Is the default value set to some arguments of
the member function, when these arguments
are not supplied with value.
Example:
Member function with default argument:
void set(const char *name, const
int GIT=40);
Can be called:
Car1.set(“Sephia”, 100);
Car2.set(“Peugeot”);
PBO III. Function & Operator Overloading
30 Minutes Exercise
1. Change the member function of your Tcomplex
class (see pre-course assignment for week 4) to
use the Function Overloading and Default
Argument.
// arithmetic
Complex add(Complex rhs);
Complex subtract(Complex rhs);
Complex multiply(Complex rhs);
Complex divide(Complex rhs);
void set_value(Complex c);
Operator Overloading
Instead of using word, it is possible to use operator
as a function name
The basic reason is that the listing easier to write
and to understand
Only predefined operator can be overloaded (such
as: +, -, *, /, %,+=, -=, *=, /*, %, ^,<, >, ==,
!=, <<, >>, ~, ! etc)
The following operator can not be overloaded
(. , .*, :: , ?:)
The hierarchy of the operator can not be changed
(for ex: x = a + b * c will do the multiplication,
addition and finally the assignment)
PBO III. Function & Operator Overloading
at3= at1.operator+(at2)
Example:
void main(){
Complex a(1,2);
Complex b(2,2);
Complex c = a+b;
c.print();
}
PBO III. Function & Operator Overloading
Test the CLOCK class in the void main, use the + and –
Clock c1(12,40,55); //12:40:55
Clock c2(4,55,14); //04:55:14
Clock C3 = c1+c2;
C3.print(); //17:36:09
Clock C4 = c1-c2;
C4.print(); //07:45:41
Kumpulkan ke [email protected] Maks 15/09/14
Format : PBO_B_Clock_nrp.zip