Download presentation
Presentation is loading. Please wait.
1
1 Review (Week2) - Control Structures C++ has only seven control structures: –Sequence structure Programs executed sequentially by default –Selection structures if, if/else, switch –Repetition structures while, do/while, for
2
2 What is the value of sum after completion of this loop? sum = 0; for(i= -5; i <=1; i++) { sum = sum -i; } (a) 1 (b) 14 (c) -14 (d) –15 b
3
3 If c is equal to 6, which of the following will be printed after execution of the following code? cout << ( x == 7 ? “ correct ” : “ incorrect ” ); (a) 6 (b) 7 (c) correct (d) incorrect
4
4 Review (Week3) - Function Functions Prepackaged functions: from the standard library programmer-defined functions Function Definitions Function Prototypes Header Files Recursion References and Reference Parameters
5
5 1// Fig. 3.4: fig03_04.cpp 2// Finding the maximum of three integers 3#include 4 5using std::cout; 6using std::cin; 7using std::endl; 8 9int maximum( int, int, int ); // function prototype 10 11int main() 12{ 13 int a, b, c; 15 cout << "Enter three integers: "; 16 cin >> a >> b >> c; 18 // a, b and c below are arguments to 19 // the maximum function call 20 cout << "Maximum is: " << maximum( a, b, c ) << endl;
6
6 Function definition Comma separate list of arguments; Data type needed for each argument; Data type of result returned. Program Output 21 22 return 0; 23} 24 25// Function maximum definition 26// x, y and z below are parameters to 27// the maximum function definition 28int maximum( int x, int y, int z ) 29{ 30 int max = x; 31 32 if ( y > max ) 33 max = y; 34 35 if ( z > max ) 36 max = z; 37 38 return max; 39} Enter three integers: 22 85 17 Maximum is: 85 Enter three integers: 92 35 14 Maximum is: 92 Enter three integers: 45 19 98 Maximum is: 98
7
7 Header Files //file MyMain.cpp #include #include “MyFunctions.h” Int main () { int ItemQuantity; double ItemPrice, Cost; ItemQuantity = 20; ItemPrice = 2.5 Cost = CalCost(ItemQuantity, ItemPrice); cout << “Total Cost is”<< Cost<<endl; Return(); } //end main() function //file MyFunctions.h Double CalCost(int Quantity, double Price); //file MyFunction.cpp #include “MyFunctions.h” Double CalCost(int Quantity, double Price) { double Cost; Cost = Quantity * Price; reture Cost; }
8
8 Example: Random Number Generation Scaling –Reduces random number to a certain range –Modulus ( % ) operator Reduces number between 0 and RAND_MAX to a number between 0 and the scaling factor –Example i = rand() % 6 + 1; Generates a number between 1 and 6
9
9 1. Define loop 2.Output random number Program Output 1// Fig. 3.7: fig03_07.cpp 2// Shifted, scaled integers produced by 1 + rand() % 6 3#include 4 5using std::cout; 6using std::endl; 7 8#include 9 10using std::setw; 11 12#include 13 14int main() 15{ 16 for ( int i = 1; i <= 20; i++ ) { 17 cout << setw( 10 ) << ( 1 + rand() % 6 ); 18 19 if ( i % 5 == 0 ) 20 cout << endl; 21 } 22 23 return 0; 24} Notice rand() % 6. This returns a number between 0 and 5 (scaling). Add 1 to get a number between 1 and 6. Executing the program again gives the same "random" dice rolls. 5 5 3 5 5 2 4 2 5 5 5 3 2 2 1 5 1 4 6 4 Program to roll dice
10
10 Recursion Example: factorial (Mathematical formulas are often expressed recursively) Definition: 3! = 3*2*1 = 6 Recursion expression: 3! = 3*2! 2! = 2*1! 1! = 1 N! can be expressed recursively as: N! = N * (N-1)! recursive case 1! = 1 base case The factorial is defined in terms of another factorial until the base case of 1! is reached
11
11 Recursion A recursive solution to the factorial problem is defined by the following function called factorial: int factorial (int number) { //base case if (number == 1) return 1; //Recursive step else return number * factorial (number - 1); }
12
12 1.4If r = 5, what is value returned by fibo function? int fibo(int r) { if(r == 0 || r== 1) return r; else return fibo(r-1) + fibo( r - 2); } (a) 0 (b) 2 (c) 3 (d) 5 d
13
13 References and Reference Parameters 3 ways to pass arguments to functions - 2 considered here and a third later Pass by value: Input values from calling function are not changed on return from called function Copy of data passed to function Changes to copy do not change original Used to prevent unwanted side effects Pass by reference: Arguments are referenced by their address and changes to contents of these addresses means the values in calling function are changed Function can directly access data Changes affect original
14
14 Function arguments #include #include //Args2.cpp void SwapbyValue( float x, float y); void SwapbyReference( float &x, float &y); int main(void) { char screenoff; float a=1.0, b=2.0; cout << "a = " << a << " b = " << b << endl; SwapbyValue (a, b); cout <<" Swap by Value\n"; cout << "a = " << a << " b = " << b << endl; SwapbyReference (a, b); cout <<" Swap by Reference\n"; cout << "a = " << a << " b = " << b << endl; cin >> screenoff; return 0; } void SwapbyValue( float x, float y) { float tmp; tmp = x; x = y; y = tmp; } void SwapbyReference( float &x, float &y) { float tmp; tmp = x; x = y; y = tmp; }
15
15 Review (Week4) - Arrays Arrays Passing Arrays to Functions Sorting Arrays Searching Arrays: Linear Search and Binary Search
16
16 Passing Arrays to Functions If array HourlyTemp has been declared as: Int HourlyTemp[24] the function call modifyArray (HourlyTemp, 24 ); passes array HourlyTemp and its size to function modifyArray C++ pass arrays to functions using simulated pass-by-reference --- the called function can modify the element values in the callers’ original arrays. The value of the name of the array is the address in the computer’s memory of the first element of the array.
17
17 Passing Arrays to Functions Function prototype The function header for function modefyArray might be written as: void modifyArray (int b[], int arraySize ); –take an integer array and a single integer; –indicating that modifyArray expects to receive the address of an array of integers in parameter b and the number of array elements in parameter arraySize. Note the strange appearance if the function prototype for modifyArray Void modifyArray (int [], int); Names optional in prototype
18
18 Passing Arrays to Functions Arrays passed-by-reference –Functions can modify original array data –Value of name of array is address of first element Function knows where the array is stored Can change original memory locations Individual array elements passed-by-value –Like regular variables –square( myArray[3] );
19
19 Sorting Arrays Sorting data –is an Important computing application –Virtually every organization must sort some data Massive amounts must be sorted Bubble sort (sinking sort) –Several passes through the array Successive pairs of elements are compared –If increasing order (or identical), no change –If decreasing order, elements exchanged –Repeat these steps for every element –If there are n elements, only n-1 passes are needed to sort the n element and only n-1 comparisons are needed for each pass.
20
20 Sorting Arrays Example: –Go left to right, and exchange elements as necessary On the first pass, the largest value sink to the bottom element; …… –Original: 3 4 2 7 6 –Pass 1: 3 2 4 6 7 (elements exchanged) –Pass 2: 2 3 4 6 7 –Pass 3: 2 3 4 6 7 (no changes needed) –Pass 4: 2 3 4 6 7 –Small elements "bubble" to the top (like 2 in this example)
21
21 Searching Arrays: Linear Search Search array for a key value Linear search –Compare each element of array with key value –Useful for small and unsorted arrays Inefficient a[1], a[2], a[3], a[4], …, a[n-1], a[n] 2 6 4 8 89 37 Key (8) compare with...
22
22 Searching Arrays: Binary Search Binary search –Only used with sorted arrays –Compare middle element with key If equal, match found If key < middle –Repeat search on first half of array If key > middle –Repeat search on last half –Very fast At most N steps, where 2 > # of elements 30 element array takes at most 5 steps 2 > 30 N 5
23
23 Review (Week5) - Pointers and Strings Pointer Variable Calling Functions by Reference Relationship Between Pointers and Arrays
24
24 Pointer Pointer variables –Contain memory addresses as values –Normally, variable contains specific value (direct reference) –Pointers contain address of variable that has specific value (indirect reference) count 7 countPtr count 7 600000 500000
25
25 Pointer Declarations –* indicates variable is pointer int *myPtr; declares pointer to int, pointer of type int * –Multiple pointers require multiple asterisks int *myPtr1, *myPtr2; –Can declare pointers to any data type float *floatPtr;
26
26 Calling Functions by Reference 3 ways to pass arguments to function –Pass-by-value –Pass-by-reference with reference arguments –Pass-by-reference with pointer arguments Arguments passed to function using reference arguments –Modify original values of arguments
27
27 Function arguments #include #include //Args2.cpp void SwapbyValue( float x, float y); void SwapbyReference( float *x, float *y); int main(void) { char screenoff; float a=1.0, b=2.0; cout << "a = " << a << " b = " << b << endl; SwapbyValue (a, b); cout <<" Swap by Value\n"; cout << "a = " << a << " b = " << b << endl; SwapbyReference (&a, &b); cout <<" Swap by Reference\n"; cout << "a = " << a << " b = " << b << endl; cin >> screenoff; return 0; } void SwapbyValue( float x, float y) { float tmp; tmp = x; x = y; y = tmp; } void SwapbyReference( float *x, float *y) { float tmp; tmp = *x; *x = *y; *y = tmp; }
28
28 Pointer Expressions and Pointer Arithmetic Pointer arithmetic –Increment/decrement pointer (++ or -- ) –Add/subtract an integer to/from a pointer( + or +=, - or -= ) –Pointers may be subtracted from each other –Pointer arithmetic meaningless unless performed on pointer to array 5 element int array on a machine using 4 byte int s –vPtr points to first element v[ 0 ], which is at location 3000 vPtr = 3000 –vPtr += 2 ; sets vPtr to 3008 vPtr points to v[ 2 ] pointer variable vPtr v[0]v[1]v[2]v[4]v[3] 30003004300830123016 location V[5]
29
29 Relationship Between Pointers and Arrays Array and Point may be used almost interchangeable Arrays and pointers closely related –Array name like constant pointer –Pointers can do array subscripting operations Assume –int b[5]; –int *bPtr; bPtr = b; bPtr = &b[0]; &b[3] bPtr+3 Array name (without a subscript)is a pointer to the first element of the array.
30
30 Relationship Between Pointers and Arrays int b[]= {10,20,30,40}; Four notation for referring to array elements –Array subscript notation b[n] e.g. b [0] = 10 b [1] = 20 b [2] = 30 b [3] = 40 –Point/offset notation where the pointer is array name *(b + n ) e.g. *(b + 0 ) = 10 *(b + 1 ) = 20 *(b + 2 ) = 30 *(b + 3 ) = 40 –Pointer subscript notation bPtr[n]e.g.bPtr[0] = 10 bPtr[1] = 20 bPtr[2] = 30 bPtr[3] = 40 –Point/offset notation *( bPtr + n ) e.g.*( bPtr + 0 ) = 10 *( bPtr + 1 ) = 20 *( bPtr + 2 ) = 30 *( bPtr + 3 ) = 40
31
31 Assuming a is an integer array of 7 items and aptr is a pointer to the array. Which of the following addresses the 4 th item of the array? (a) a[4] (b) *aptr (c) &a[3] (d) *(aptr+4) c
32
32 Review (Week6) - Classes and Data Abstraction Structure Class Initializing Class Objects: Constructors
33
33 Structure Definitions Structures –Aggregate data types built using elements of other types struct Time { int hour; int minute; int second; }; Structure member naming –In same struct : must have unique names –In different struct s: can share name struct definition must end with semicolon Structure tag Structure members
34
34 Structure Definitions struct definition –Creates new data type used to declare variables –Structure variables declared like variables of other types –Examples: Time timeObject; Time timeArray[ 10 ]; Time *timePtr; Time &timeRef = timeObject;
35
35 Accessing Structure Members Member access operators –Dot operator (. ) accesses a structure or a class members via the variable name for the object or via a reference to the object. cout << timeObject.hour; cout << timeRef.hour; –Arrow operator ( -> ) accesses a structure or a class members via pointer to object cout hour; –timePtr->hour same as ( *timePtr ).hour Parentheses required –* lower precedence than.
36
36 // example about structures #include using namespace std; struct movies { string title; int year; } ; int main () { movies mine; mine.title = "2001 A Space Odyssey"; mine.year = 1968; cout << "My favorite movie is:\n "; cout << mine.title; cout << " (" << mine.year << ")\n"; return 0; } My favorite movie is: 2001 A Space Odyssey (1968)
37
37 // example: class constructor #include using namespace std; class CRectangle { int width, height; public: CRectangle (int=5,int=5); int area (void) {return (width*height);} }; CRectangle::CRectangle (int a, int b) { width = a; height = b; } int main () { CRectangle recta (3,4); CRectangle rectb; CRectangle rectc(3); cout << "recta area: " << recta.area() << endl; cout << "rectb area: " << rectb.area() << endl; cout << "rectc area: " << rectc.area() << endl; return 0; } recta area: 12 rectb area: 25 rectc area: 15
38
38 Review (Week7) - Classes Part II Composition: Objects as Members of Classes Dynamic Memory static Class Members Operator Overloading
39
39 Dynamic Memory Management with Operators new and delete To use pointers you much follow four steps: 1.Declare the pointer variable Int *FredsPtr; 2.Reserve a space in memory for the value FredsPtr = new int; 3.Assign a value for the pointer *FredsPtr = 30; 4.Use delete to free the memory Delete FredsPtr; AddressContents 0x8566fff7??? 0x8566fff6??? 0x8566fff5??? 0x8566fff445 Contents ??? FredsPtr ??? AddressContents 0x8566fff7??? 0x8566fff6??? 0x8566fff5??? 0x8566fff445 Contents 0x8566fff6 FredsPtr AddressContents 0x8566fff7??? 0x8566fff630 0x8566fff5??? 0x8566fff445 Contents 0x8566fff6 FredsPtr *FredsPtr AddressContents 0x8566fff7??? 0x8566fff6??? 0x8566fff5??? 0x8566fff445 Contents ??? FredsPtr ???
40
40 Dynamic Memory Management with Operators new and delete new 1. Can declare and reserve a space in one line: Int *FredsPtr = new int; Int *FredsPtr; FredsPtr = new int ; 2. Providing initializers double *ptr = new double( 3.14159 ); Time *timePtr = new Time( 12, 0, 0 ); 3. Allocating arrays int *gradesArray = new int[ 10 ];
41
41 Dynamic Memory Management with Operators new and delete The NULL pointer Int main() { Int *FredsPtr = NULL; if (FredsPtr = = NULL){// if the pointer is NULL FredsPtr = new int;//then create a new pointer *FredsPtr = 30;//and give it a value } AddressContents 0x8566fff7??? 0x8566fff630 0x8566fff5??? 0x8566fff445 Contents 0x8566fff6 FredsPtr *FredsPtr AddressContents 0x8566fff7??? 0x8566fff630 0x8566fff5??? 0x8566fff445 NULL Contents NULL FredsPtr
42
42 #include using namespace std; int main () { int i,n; int * p; cout << "How many numbers would you like to type? "; cin >> i; p= new int[i]; if (p == 0) cout << "Error: memory could not be allocated"; else { for (n=0; n<i; n++) { cout << "Enter number: "; cin >> p[n]; } cout << "You have entered: "; for (n=0; n<i; n++) cout << p[n] << ", "; delete[] p; } return 0; } How many numbers would you like to type? 5 Enter number : 75 Enter number : 436 Enter number : 1067 Enter number : 8 Enter number : 32 You have entered: 75, 436, 1067, 8, 32, 1.Declare the pointer variable 2.Reserve a space in memory for the value 3.Assign a value for the pointer 4.Use delete to free the memory
43
43 Operator Overloading Types –Built in ( int, char ) or user-defined –Can use existing operators with user-defined types Cannot create new operators Overloading operators –Create a function for the class –Name function operator followed by symbol Operator+ for the addition operator +
44
44 Operator Overloading C++ incorporates the option to use standard operators to perform operations with classes in addition to with fundamental types. For example: int a, b, c; a = b + c; This is obviously valid code in C++, since the different variables of the addition are all fundamental types. Nevertheless, it is not so obvious that we could perform an operation similar to the following one: struct { string product; float price; } a, b, c; a = b + c; In fact, this will cause a compilation error. However, we can design classes able to perform operations using standard operators.
45
45 // vectors: overloading operators example #include using namespace std; class CVector { public: int x,y; CVector (int=0, int=0); CVector operator + (CVector); }; CVector::CVector (int a, int b) { x = a; y = b; } CVector CVector::operator+ (CVector param) { CVector temp; temp.x = x + param.x; temp.y = y + param.y; return (temp); } int main () { CVector a (3,1); CVector b (1,2); CVector c; c = a + b; cout << c.x << "," << c.y; return 0; } 4,3 CVector (int, int); // function name CVector (constructor) CVector operator+ (CVector); // function returns a CVector c = a + b; c = a.operator+ (b); type operator sign (parameters) { /*...*/ }
46
46 // operator_overloading.cpp #include using namespace std; class Complex { public: Complex( double r, double i ) : re(r), im(i) { } Complex operator-( Complex &other ); void Display( ) { cout << re << ", " << im << endl; } private: double re, im; }; // Operator overloaded using a member function Complex Complex::operator-( Complex &other ) { return Complex( re - other.re, im - other.im ); } int main() { Complex a = Complex( 1.2, 3.4 ); Complex b = Complex( 5.6, 7.8 ); Complex c = Complex( 0.0, 0.0 ); c = a - b; c.Display(); } -4.4, -4.4 c = a - b; c = a.operator- (b);
47
47 Review (Week8) _Inheritance Base Classes and Derived Classes
48
48 point3.h (1 of 1) 1 // Fig. 9.17: point3.h 2 // Point3 class definition represents an x-y coordinate pair. 3 #ifndef POINT3_H 4 #define POINT3_H 5 6 class Point3 { 7 8 public: 9 Point3( int = 0, int = 0 ); // default constructor 10 11 void setX( int ); // set x in coordinate pair 12 int getX() const; // return x from coordinate pair 13 14 void setY( int ); // set y in coordinate pair 15 int getY() const; // return y from coordinate pair 16 17 void print() const; // output Point3 object 18 19 private: 20 int x; // x part of coordinate pair 21 int y; // y part of coordinate pair 22 23 }; // end class Point3 24 25 #endif Better software-engineering practice: private over protected when possible. // default constructor Point3::Point3( int xValue, int yValue ) : x( xValue ), y( yValue ) { // empty body } // end Point3 constructor
49
49 point3.cpp (1 of 2) 1 // Fig. 9.18: point3.cpp 2 // Point3 class member-function definitions. 3 #include 4 5 using std::cout; 6 7 #include "point3.h" // Point3 class definition 8 9 // default constructor 10 Point3::Point3( int xValue, int yValue ) 11 : x( xValue ), y( yValue ) 12 { 13 // empty body 14 15 } // end Point3 constructor 16 17 // set x in coordinate pair 18 void Point3::setX( int xValue ) 19 { 20 x = xValue; // no need for validation 21 22 } // end function setX 23 Member initializers specify values of x and y.
50
50 point3.cpp (2 of 2) 24 // return x from coordinate pair 25 int Point3::getX() const 26 { 27 return x; 28 29 } // end function getX 30 31 // set y in coordinate pair 32 void Point3::setY( int yValue ) 33 { 34 y = yValue; // no need for validation 35 36 } // end function setY 37 38 // return y from coordinate pair 39 int Point3::getY() const 40 { 41 return y; 42 43 } // end function getY 44 45 // output Point3 object 46 void Point3::print() const 47 { 48 cout << '[' << getX() << ", " << getY() << ']'; 49 50 } // end function print Invoke non- private member functions to access private data.
51
51 circle4.h (1 of 1) 1 // Fig. 9.19: circle4.h 2 // Circle4 class contains x-y coordinate pair and radius. 3 #ifndef CIRCLE4_H 4 #define CIRCLE4_H 5 6 #include "point3.h" // Point3 class definition 7 8 class Circle4 : public Point3 { 9 10 public: 11 12 // default constructor 13 Circle4( int = 0, int = 0, double = 0.0 ); 14 15 void setRadius( double ); // set radius 16 double getRadius() const; // return radius 17 18 double getDiameter() const; // return diameter 19 double getCircumference() const; // return circumference 20 double getArea() const; // return area 21 22 void print() const; // output Circle4 object 23 24 private: 25 double radius; // Circle4's radius 26 27 }; // end class Circle4 28 #endif Class Circle4 inherits from class Point3. Maintain private data member radius. Circle4::Circle4( int xValue, int yValue, double radiusValue ) : Point3( xValue, yValue ) // call base-class constructor { setRadius( radiusValue ); } void Circle4::setRadius( double radiusValue ) { radius = ( radiusValue < 0.0 ? 0.0 : radiusValue ); }
52
52 circle4.cpp (1 of 2) 1 // Fig. 9.20: circle4.cpp 2 // Circle4 class member-function definitions. 3 #include 4 5 using std::cout; 6 7 #include "circle4.h" // Circle4 class definition 8 9 // default constructor 10 Circle4::Circle4( int xValue, int yValue, double radiusValue ) 11 : Point3( xValue, yValue ) // call base-class constructor 12 { 13 setRadius( radiusValue ); 14 15 } // end Circle4 constructor 16 17 // set radius 18 void Circle4::setRadius( double radiusValue ) 19 { 20 radius = ( radiusValue < 0.0 ? 0.0 : radiusValue ); 21 22 } // end function setRadius 23 24 // return radius 25 double Circle4::getRadius() const 26 { 27 return radius; 28 } // end function getRadius 29 30 Base-class initializer syntax passes arguments to base class Point3.
53
53 circle4.cpp (2 of 2) 31 // calculate and return diameter 32 double Circle4::getDiameter() const 33 { 34 return 2 * getRadius(); 35 36 } // end function getDiameter 37 38 // calculate and return circumference 39 double Circle4::getCircumference() const 40 { 41 return 3.14159 * getDiameter(); 42 43 } // end function getCircumference 44 45 // calculate and return area 46 double Circle4::getArea() const 47 { 48 return 3.14159 * getRadius() * getRadius(); 49 50 } // end function getArea 51 52 // output Circle4 object 53 void Circle4::print() const 54 { 55 cout << "Center = "; 56 Point3::print(); // invoke Point3's print function 57 cout << "; Radius = " << getRadius(); 58 } // end function print Invoke function getRadius rather than directly accessing data member radius. Redefine class Point3 ’s member function print. Invoke base-class Point3 ’s print function using binary scope-resolution operator ( :: ).
54
54 Review (Week9) _Polymorphism Relationships Among Objects in an Inheritance Hierarchy Invoking Base-Class Functions from Derived-Class object Virtual Functions
55
55 point.h (1 of 1) 1 // Fig. 10.8: point.h 2 // Point class definition represents an x-y coordinate pair. 3 #ifndef POINT_H 4 #define POINT_H 5 6 class Point { 7 8 public: 9 Point( int = 0, int = 0 ); // default constructor 10 11 void setX( int ); // set x in coordinate pair 12 int getX() const; // return x from coordinate pair 13 14 void setY( int ); // set y in coordinate pair 15 int getY() const; // return y from coordinate pair 16 17 virtual void print() const; // output Point object 18 19 private: 20 int x; // x part of coordinate pair 21 int y; // y part of coordinate pair 22 23 }; // end class Point 24 25 #endif Print declared virtual. It will be virtual in all derived classes.
56
56 circle.h (1 of 1) 1 // Fig. 10.9: circle.h 2 // Circle class contains x-y coordinate pair and radius. 3 #ifndef CIRCLE_H 4 #define CIRCLE_H 5 6 #include "point.h" // Point class definition 7 8 class Circle : public Point { 9 10 public: 11 12 // default constructor 13 Circle( int = 0, int = 0, double = 0.0 ); 14 15 void setRadius( double ); // set radius 16 double getRadius() const; // return radius 17 18 double getDiameter() const; // return diameter 19 double getCircumference() const; // return circumference 20 double getArea() const; // return area 21 22 virtual void print() const; // output Circle object 23 24 private: 25 double radius; // Circle's radius 26 27 }; // end class Circle 28 #endif
57
57 fig10_10.cpp (1 of 2) 1 // Fig. 10.10: fig10_10.cpp 2 // Introducing polymorphism, virtual functions and dynamic 3 // binding. 4 #include 5 6 using std::cout; 7 using std::endl; 8 using std::fixed; 9 10 #include 11 12 using std::setprecision; 13 14 #include "point.h" // Point class definition 15 #include "circle.h" // Circle class definition 16 17 int main() 18 { 19 Point point( 30, 50 ); 20 Point *pointPtr = 0; 21 22 Circle circle( 120, 89, 2.7 ); 23 Circle *circlePtr = 0; 24 25 // set floating-point numeric formatting 26 cout << fixed << setprecision( 2 ); 27
58
58 fig10_10.cpp (2 of 2) 28 // output objects point and circle using static binding 32 point.print(); // static binding 33 cout << "\nCircle: "; 34 circle.print(); // static binding 35 36 // output objects point and circle using dynamic binding 39 40 // aim base-class pointer at base-class object and print 41 pointPtr = &point; 45 pointPtr->print(); 46 47 // aim derived-class pointer at derived-class 48 // object and print 49 circlePtr = &circle; 53 circlePtr->print(); 54 55 // aim base-class pointer at derived-class object and print 56 pointPtr = &circle; 60 pointPtr->print(); // polymorphism: invokes circle's print 61 cout << endl; 62 63 return 0; 64 } // end main At run time, the program determines that pointPtr is aiming at a Circle object, and calls Circle ’s print function. This is an example of polymorphism. Point: [30, 50] Circle: Center = [120, 89]; Radius = 2.70 [30, 50] Center = [120, 89]; Radius = 2.70
59
59 Review (Week10) _ Templates and File Processing Templates Function Templates Class Templates File Processing Sequential-Access File Random-Access Files
60
60 Function Templates Function-template definitions –Keyword template –List formal type parameters in angle brackets ( ) Each parameter preceded by keyword class or typename –class and typename interchangeable template Specify types of –Arguments to function –Return type of function –Variables within function
61
61 #include //Tplate2.cpp #define max 5 template Tpt SumArray(const Tpt a[], int ) { int i; Tpt sum; sum = a[0]; for( i=1; i < max; i++)sum = sum + a[i]; return sum; } int main(void) { char screenoff; int a[max] = {1,2,3,4,5}; float b[max]= {1.1, 2.2, 3.3, 4.4, 5.5}; cout << "Number sum : " << SumArray(a, max) << endl; cout << "Number sum : " << SumArray(b, max) << endl; cin >> screenoff; }
62
62 Class Templates Stack –LIFO (last-in-first-out) structure Class templates –Generic programming –Describe notion of stack generically Instantiate type-specific version –Parameterized types Require one or more type parameters –Customize “generic class” template to form class-template specialization
63
63 Files and Streams To perform file processing –Include and –Class templates basic_ifstream (input) basic_ofstream (output) basic_fstream (I/O) –typedef s for specializations that allow char I/O ifstream ( char input) ofstream ( char output) fstream ( char I/O)
64
64 // writing on a text file #include using namespace std; int main () { //ofstream myfile ("example.txt"); ofstream myfile; myfile.open ("example.txt"); if (myfile.is_open()) { myfile << "This is a line./n"; myfile << "This is another line./n"; myfile.close(); } else cout << "Unable to open file"; return 0; } [file example.txt] This is a line. This is another line.
65
65 fig14_04.cpp (1 of 2) 1 // Fig. 14.4: fig14_04.cpp 2 // Create a sequential file. 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::ios; 8 using std::cerr; 9 using std::endl; 10 11 #include 12 13 using std::ofstream; 14 15 #include // exit prototype 16 17 int main() 18 { 19 // ofstream constructor opens file 20 ofstream outClientFile( "clients.dat", ios::out ); 21 22 // exit program if unable to create file 23 if ( !outClientFile ) { // overloaded ! operator 24 cerr << "File could not be opened" << endl; 25 exit( 1 ); 26 27 } // end if Notice the the header files required for file I/O. ofstream object created and used to open file "clients.dat". If the file does not exist, it is created. ! operator used to test if the file opened properly.
66
66 fig14_04.cpp (2 of 2) 28 29 cout << "Enter the account, name, and balance." << endl 30 << "Enter end-of-file to end input.\n? "; 31 32 int account; 33 char name[ 30 ]; 34 double balance; 35 36 // read account, name and balance from cin, then place in file 37 while ( cin >> account >> name >> balance ) { 38 outClientFile << account << ' ' << name << ' ' << balance 39 << endl; 40 cout << "? "; 41 42 } // end while 43 44 return 0; // ofstream destructor closes file 45 46 } // end main cin is implicitly converted to a pointer. When EOF is encountered, it returns 0 and the loop stops. Write data to file like a regular stream. Enter the account, name, and balance. Enter end-of-file to end input. ? 100 Jones 24.98 ? 200 Doe 345.67 ? 300 White 0.00 ? 400 Stone -42.16 ? 500 Rich 224.62 ? ^Z File closed when destructor called for object. Can be explicitly closed with close(). fig14_04.cpp output (1 of 1)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.