Review of Function Overloading - PowerPoint PPT Presentation

About This Presentation
Title:

Review of Function Overloading

Description:

This is a powerful C feature that allows the use of operators for user defined classes, e.g. ... example usage: cout v1 v2 v3; int i; ... – PowerPoint PPT presentation

Number of Views:20
Avg rating:3.0/5.0
Slides: 9
Provided by: bman
Category:

less

Transcript and Presenter's Notes

Title: Review of Function Overloading


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 xx
  • double sqr(double x) return xx
  • double sqr(double x, double y) return xy
  • int i 2 double x 1.2, y 2.0
  • cout ltlt sqr(i) ltlt ltlt sqr(x) ltlt ltlt
    sqr(x,y)
  • 4 1.44 2.4

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
AB // is overloaded (dot product) cout ltlt D
// ltlt is overloaded Similar to function
overloading except it uses operators
3
Member Operator Functions
General form return-type class-nameoperator(ar
gument-list) // operation to be performed
e.g. void dVectoroperator(dVector v2) //
v1 v2 int i if ( n1 ! v2.n1 n2 ! v2.n2 )
return // error ! for ( i n1 i lt n2 i )
e(i) v2.e(i) // copy elements
4
Improved Operator
dVector dVectoroperator(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 lt n2 i )
ans-gte(i) e(i) v2.e(i) // copy
elements return ans
5
Overloading the Operator
dVector dVectoroperator(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 lt n2 i )
ans-gte(i) e(i) v2.e(i) // copy
elements return ans
6
Overloading Unary Operators
Example Norm operator double
dVectoroperator!() int i double ans0.0 //
declare a return variable for ( i n1 i lt 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 ltlt n.x
number n1 show_x(n1) ? 7.11
8
ltlt Operator Overloading
class dVector friend ostream operatorltlt(ostream
stream, dVector v) ostream
operatorltlt(ostream stream, dVector v) //
example usage cout ltlt v1 ltlt v2 ltlt v3 int i for
( i v.n1 i lt v.n2 i ) stream ltlt "\n" ltlt
v.e(i) return stream
Write a Comment
User Comments (0)
About PowerShow.com