ECE 538 Object Oriented Concepts Session 10 - PowerPoint PPT Presentation

1 / 28
About This Presentation
Title:

ECE 538 Object Oriented Concepts Session 10

Description:

Suppose we want a function that returns the absolute value of a number ... T abs(T n) return (n 0) ? n: n; Tempabs // tempabs.cpp ... – PowerPoint PPT presentation

Number of Views:69
Avg rating:3.0/5.0
Slides: 29
Provided by: johngwe
Category:

less

Transcript and Presenter's Notes

Title: ECE 538 Object Oriented Concepts Session 10


1
ECE 538 Object Oriented ConceptsSession 10
  • Dr. John G. Weber
  • John.Weber_at_notes.udayton.edu
  • http//academic.udayton.edu/JohnWeber

2
Templates and Exceptions
  • Templates
  • Use one function or class to handle different
    data types
  • Exceptions
  • Uniform way to handle errors in classes

3
Function Templates
  • Suppose we want a function that returns the
    absolute value of a number
  • Must write for a given data type
  • e.g. int absolute (int n)
  • return (n lt 0) ? n n //if n is negative,
    return n
  • Now if we want a function that works for longs,
    we need to write another function substituting
    long for int in the above
  • Same for floats
  • Function body is same for each type
  • Function names can be the same (overloaded)
  • Must have separate definitions

4
Function Templates (Cont)
  • Want to write a function once and have it work
    for different data types
  • Write a template for the function
  • Data type determines how it is interpreted
  • Simple template for the absolute value functions
  • template ltclass Tgt //function template
  • T abs(T n)
  • return (n lt 0) ? n n

5
Tempabs
// tempabs.cpp // template used for absolute
value function include ltiostreamgt using
namespace std //---------------------------------
----------------------------- template ltclass Tgt
//function template T abs(T n)
return (n lt 0) ? -n n //---------------------
----------------------------------------- int
main() int int1 5 int int2 -6 long
lon1 70000L long lon2 -80000L double dub1
9.95 double dub2 -10.15
//calls instantiate functions cout
ltlt "\nabs(" ltlt int1 ltlt ")" ltlt abs(int1)
//abs(int) cout ltlt "\nabs(" ltlt int2 ltlt ")" ltlt
abs(int2) //abs(int) cout ltlt "\nabs(" ltlt lon1
ltlt ")" ltlt abs(lon1) //abs(long) cout ltlt
"\nabs(" ltlt lon2 ltlt ")" ltlt abs(lon2)
//abs(long) cout ltlt "\nabs(" ltlt dub1 ltlt ")" ltlt
abs(dub1) //abs(double) cout ltlt "\nabs(" ltlt
dub2 ltlt ")" ltlt abs(dub2) //abs(double) cout
ltlt endl return 0
6
Syntax
  • Represent the data type used in the function by
    name that stands for any type (e.g. T in the
    previous example)
  • The name is arbitrary
  • Template keyword tells compiler we are defining a
    template
  • Class keyword inside angle brackets say we are
    defining a type
  • Variable following class keyword is the template
    argument
  • Use template argument throughout the function
    definition in place of specific data type

7
Compiler Actions
  • Function template does not generate code
  • Function call generates code
  • Compiler gets type from function call
  • Generates specific function for the specific type
  • Called instantiating the function template
  • Each instance of function is called template
    function
  • Compiler generates only one version of the
    template for each type

8
Function Template with Multiple Arguments
// tempfind.cpp // template used for function
that finds number in array include
ltiostreamgt using namespace std // function
returns index number of item, or -1 if not
found template ltclass atypegt int find(atype
array, atype value, int size) for(int j0
jltsize j) if(arrayjvalue) return
j return -1 //-----------------------------
--------------------------------- char chrArr
1, 3, 5, 9, 11, 13 //array char ch 5
//value to find int
intArr 1, 3, 5, 9, 11, 13 int in
6 long lonArr 1L, 3L, 5L, 9L, 11L,
13L long lo 11L double dubArr 1.0, 3.0,
5.0, 9.0, 11.0, 13.0 double db
4.0 //-------------------------------------------
-------------------- int main() cout ltlt "\n 5
in chrArray index" ltlt find(chrArr, ch,
6) cout ltlt "\n 6 in intArray index" ltlt
find(intArr, in, 6) cout ltlt "\n11 in lonArray
index" ltlt find(lonArr, lo, 6) cout ltlt "\n 4
in dubArray index" ltlt find(dubArr, db, 6)
cout ltlt endl return 0
  • Template argument named atype
  • atype is the type of the pointer to array
  • atype is the type of the item to be matched
  • Third argument is int type not a template argument

9
More
  • Template arguments must match
  • All instances of template argument must be the
    same within a given function invocation
  • e.g. int intarray 1, 3, 5, 7 //int
    array
  • float f1 5.0 //float value
  • int value find(intarray, f1, 4) //will not
    work
  • Additional template arguments
  • Examplearray size in find function may require a
    long
  • template ltclass atype, class btypegt
  • btype find (atype array, atype value, btype
    size)
  • for (btype j0 j lt size j)
  • if(arrayj value)
  • return j
  • return static_castltbtypegt (-1)

10
Restrictions
  • Know what types can work with your template
    function
  • Make sure the operators used are appropriate for
    all types supported
  • Hint
  • Start with a normal function when developing a
    template

11
Class Templates
  • Extend template function concept to classes
  • Generally used for data storage (container)
    classes
  • For exampleclass Stack
  • class Stack
  • private
  • int stmax //array of int
  • int top //top of stack
  • public
  • Stack() //constructor
  • void push (int var) //pushes an integer onto
    the stack
  • int pop() //returns int from stack
  • If you want a stack of longs, need to rewrite

12
Stack Template
// tempstak.cpp // implements stack class as a
template include ltiostreamgt using namespace
std const int MAX 100 ////////////////////////
//////////////////////////////////////// template
ltclass Typegt class Stack private Type
stMAX //stack array of any type
int top //number of top of
stack public Stack()
//constructor top -1 void
push(Type var) //put number on stack
sttop var Type pop()
//take number off stack return
sttop-- ///////////////////////////////
/////////////////////////////////
13
Stack Template (main routine)
int main() Stackltfloatgt s1 //s1 is
object of class Stackltfloatgt
s1.push(1111.1F) //push 3 floats, pop 3
floats s1.push(2222.2F) s1.push(3333.3F)
cout ltlt "1 " ltlt s1.pop() ltlt endl cout ltlt
"2 " ltlt s1.pop() ltlt endl cout ltlt "3 " ltlt
s1.pop() ltlt endl Stackltlonggt s2 //s2
is object of class Stackltlonggt
s2.push(123123123L) //push 3 longs, pop 3
longs s2.push(234234234L)
s2.push(345345345L) cout ltlt "1 " ltlt s2.pop()
ltlt endl cout ltlt "2 " ltlt s2.pop() ltlt endl
cout ltlt "3 " ltlt s2.pop() ltlt endl return 0
14
Use
  • Definition similar to that used in defining
    template functions
  • template ltclass Typegt //signals entire class
    following will be template
  • class Stack //template argument is Type
  • //data and member functions written using
    template argument
  • Class templates instantiated by defining an
    object using the template argument
  • e.g. Stackltfloatgt s1 //creates a stack
    s1 that stores floating pt numbers
  • Note the type of s1 is Stackltfloatgt
  • A stack if integers would be created by
    Stackltintgt s2

15
Defining Member Functions outside the class
specification
  • Define template class as before
  • Use templateltclass Typegt as start to each
    function definition
  • The use StackltTypegt as the namespace qualifier
    for the function

16
Template Class Definition Example
// temstak2.cpp // implements stack class as a
template // member functions are defined outside
the class include ltiostreamgt using namespace
std const int MAX 100 ////////////////////////
//////////////////////////////////////// template
ltclass Typegt class Stack private
Type stMAX //stack array of any
type int top //number of
top of stack public Stack() //constructor
void push(Type var) //put number on
stack Type pop() //take
number off stack ///////////////////////////
/////////////////////////////////////
17
External Function Definition
templateltclass Typegt StackltTypegtStack()
//constructor top -1
//----------------------------------------------
---------------- templateltclass Typegt void
StackltTypegtpush(Type var) //put number on
stack sttop var
//----------------------------------------------
---------------- templateltclass Typegt Type
StackltTypegtpop() //take number off
stack return sttop--
//----------------------------------------------
----------------
18
Main Program
int main() Stackltfloatgt s1 //s1 is
object of class Stackltfloatgt
s1.push(1111.1F) //push 3 floats, pop 3
floats s1.push(2222.2F) s1.push(3333.3F)
cout ltlt "1 " ltlt s1.pop() ltlt endl cout ltlt
"2 " ltlt s1.pop() ltlt endl cout ltlt "3 " ltlt
s1.pop() ltlt endl Stackltlonggt s2 //s2
is object of class Stackltlonggt
s2.push(123123123L) //push 3 longs, pop 3
longs s2.push(234234234L)
s2.push(345345345L) cout ltlt "1 " ltlt s2.pop()
ltlt endl cout ltlt "2 " ltlt s2.pop() ltlt endl
cout ltlt "3 " ltlt s2.pop() ltlt endl return 0
19
Template Class Name
  • Expressed differently in different contexts
  • Within Class Specification
  • Simply the name e.g. Stack
  • For externally defined member functions
  • Class name plus template argument name e.g.
    StackltTypegt
  • Object instantiation
  • Class name plus specific type e.g. Stackltfloatgt
  • Return Type
  • Class name plus template type

20
A Linked List Class
  • Links objects of class linklist (objects are data
    structures)
  • Structure contains a single data item
  • Pointer to next item in list
  • List stores pointer to head of list
  • Last item in list has null pointer

21
Linked List Example
// linklist.cpp // linked list include
ltiostreamgt using namespace std //////////////////
////////////////////////////////////////////// str
uct link //one element
of list int data
//data item link next
//pointer to next link ////////////////////
//////////////////////////////////////////// class
linklist //a list of
links private link first
//pointer to first link public
linklist() //no-argument
constructor first NULL
//no first link void additem(int d)
//add data item (one link) void
display() //display all links
//---------------------------------------------
-----------------
22
Example Member Functions
void linklistadditem(int d) //add data
item link newlink new link
//make a new link newlink-gtdata d
//give it data newlink-gtnext first
//it points to next link first
newlink //now first points to
this //--------------------------------------
------------------------ void linklistdisplay()
//display all links link
current first //set ptr to first
link while( current ! NULL ) //quit
on last link cout ltlt current-gtdata
ltlt endl //print data current
current-gtnext //move to next link
///////////////////////////////////////////
/////////////////////
23
Example Main
int main() linklist li //make
linked list li.additem(25) //add four
items to list li.additem(36)
li.additem(49) li.additem(64)
li.display() //display entire list
return 0
24
Now a Linked List with Templates
  • Make linklist class into a template
  • Make link structure into a template

25
Class
// templist.cpp // implements linked list as a
template include ltiostreamgt using namespace
std /////////////////////////////////////////////
/////////////////// templateltclass TYPEgt
//struct linkltTYPEgt struct link
//one element of list //( within
this struct def link means linkltTYPEgt )
TYPE data //data item
link next //pointer to
next link //////////////////////////////////
////////////////////////////// templateltclass
TYPEgt //class linklistltTYPEgt clas
s linklist //a list of
links //(within this class, linklist means
linklistltTYPEgt) private
linkltTYPEgt first //pointer to
first link public linklist()
//no-argument constructor
first NULL //no first link
//note destructor would be nice not shown for
simplicity void additem(TYPE d)
//add data item (one link) void
display() //display all links
///////////////////////////////////////////////
/////////////////
26
Member Functions
templateltclass TYPEgt void linklistltTYPEgtadditem(
TYPE d) //add data item linkltTYPEgt
newlink new linkltTYPEgt //make a new link
newlink-gtdata d //give it
data newlink-gtnext first //it
points to next link first newlink
//now first points to this
//----------------------------------------------
---------------- templateltclass TYPEgt void
linklistltTYPEgtdisplay() //display all
links linkltTYPEgt current first
//set ptr to first link while( current ! NULL
) //quit on last link
cout ltlt endl ltlt current-gtdata //print data
current current-gtnext //move to next
link //------------------------------
--------------------------------
27
Example Main
int main() linklistltdoublegt ld //ld is
object of class linklistltdoublegt
ld.additem(151.5) //add three doubles to list
ld ld.additem(262.6) ld.additem(373.7)
ld.display() //display entire list ld
linklistltchargt lch //lch is object of class
linklistltchargt lch.additem('a') //add
three chars to list lch lch.additem('b')
lch.additem('c') lch.display()
//display entire list lch cout ltlt endl
return 0
28
User Defined Data Types
  • Again, must make sure that operators used are
    available
  • May need to overload operator to make work
  • Try this for the Employ program that we used to
    study inheritance
  • Put objects of type employee into linked list
  • Will need to overload gtgt and ltlt operators from
    iostream
Write a Comment
User Comments (0)
About PowerShow.com