Title: Chapter 123 Discovering C
1Chapter 12-3Discovering C
2Polymorphism
- Indicates that the same word or symbol can have
different meanings - overloading function names, overloading
operators, and templates - Function name overloading
- ex) Constructors
- The same functions have different parameter lists
- During compilation, the compiler inspect the
number and type of the actual parameters
3Operator overloading
- Allows operator symbols to have different
meanings with different types - ex) ltlt
- integer bitwise left shift
- takes an ostream object as its left operand and
either a string or one of the fundamental types
as its right operand - gtgt
- Most operators in C can be overloaded.
4Operator overloading (II)
- In C, operator is regarded as a function
- ex) for operator _at_
- the function name is operator_at_
- parameters are the left and right data of the _at_
- int result, a, b
- result ab //result operator(a,b)
- Overloading operators is done in the context of
classes - At least one of the operands of an overloaded
operator must be of a class type - Unary operator
- ex) result _at_data
- result data_at_
- MyClass operator_at_(MyClass data)
5Operator overloading (III)
- class Complex
- private
- float real, imag
- public
- Complex()realimag0
- Complex(int r, int i) realr imagi
- Complex operator-()
- friend Complex operator(Complex c)
-
- Complex Complexoperator-()
- Compex c
- c.real-real
- c.imag-imag
- return c
-
- Complex operator(Complex c1)
- Complex c2
- c2.realc1.real
- c2.imag-c1.imag
Complex c1, c2(1,5) //c100i, c215i c1-c2
//c1-1-5i //c1c2.operator-() c1c2
//c11-5i //c1operator-(c2)
this
6Operator overloading (IV)
- class Complex
- ....
- public
- ....
- Complex operator(Complex c)
- friend Complex operator-(Complex c1, Complex
c2) -
- Complex Complexoperator(Complex c)
- Complex c3
- c3.realrealc.real
- c3.imagimagc.imag
- return c3
-
- Complex operator-(Complex c1, Complex c2)
- Complex c3
- c3.realc1.realc2.real
- c3.imagc1.imagc2.imag
- return c3
-
Complex comp1,comp2,comp3 .... comp3comp1comp2
//comp3comp1.operator( comp2) comp3comp1-co
mp2 //comp3operator-(comp1,comp2)
this