C++ Program Design An Introduction to Programming and Object-Oriented Design.

Slides:



Advertisements
Similar presentations
True or false A variable of type char can hold the value 301. ( F )
Advertisements

C++ Basics Prof. Shermane Austin. Learning Programming Language Basics Data Types – simple Expressions Relational and Logical Operators Conditional Statements.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Templates and Polymorphism Generic functions and classes.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Pointers and Dynamic Objects Mechanisms for developing flexible list representations.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. The Fundamentals of C++ Basic programming elements and concepts.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
The Fundamentals of C++ Basic programming elements and concepts JPC and JWD © 2002 McGraw-Hill, Inc.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
1 Midterm Review COMP 102. Tips l Eat a light meal before the exam l NO electronic devices (including calculators, dictionaries, phones, pagers, etc.)
Chapter 2 Data Types, Declarations, and Displays
Chapter 2: Introduction to C++.
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
C++ fundamentals.
Basic Elements of C++ Chapter 2.
C++ Programming Language Day 1. What this course covers Day 1 – Structure of C++ program – Basic data types – Standard input, output streams – Selection.
Review of C++ Programming Part II Sheng-Fang Huang.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Templates and Polymorphism Generic functions and classes
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
High-Level Programming Languages: C++
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Modifying objects Operators and Expressions.
Modifying objects Operators and Expressions JPC and JWD © 2002 McGraw-Hill, Inc.
EzWindows API A Graphical Application Programmer Interface JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Introduction to C++ Systems Programming. Systems Programming: Introduction to C++ 2 Systems Programming: 2 Introduction to C++  Syntax differences between.
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
Programming Language C++ Xulong Peng CSC415 Programming Languages.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Pointers and Dynamic Objects Mechanisms for developing flexible list representations JPC and JWD © 2002 McGraw-Hill, Inc.
1 C++ Syntax and Semantics, and the Program Development Process.
Chapter 2. C++ Program Structure C++ program is a collection of subprograms Subprograms in C++ are called FUNCTIONS Each function performs a specific.
The Fundamentals of C++ Chapter 2: Basic programming elements and concepts JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
C++ Programming: Basic Elements of C++.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
CIS-165 C++ Programming I CIS-165 C++ Programming I Bergen Community College Prof. Faisal Aljamal.
1 COMS 261 Computer Science I Title: String Class Date: October 3, 2005 Lecture Number: 14.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
1 COMS 261 Computer Science I Title: Functions Date: October 12, 2005 Lecture Number: 17.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 9, 2005 Lecture Number: 6.
Inheritance Mechanism for deriving new classes from existing classes Chapter 13.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
C++ Basics Programming. COMP104 Lecture 5 / Slide 2 Introduction to C++ l C is a programming language developed in the 1970s with the UNIX operating system.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 15, 2004 Lecture Number: 11.
Chapter 1.2 Introduction to C++ Programming
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ Systems Programming.
Basic Elements of C++.
Basic Elements of C++ Chapter 2.
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
COMS 261 Computer Science I
Chapter 2: Introduction to C++.
Engineering Problem Solving with C++ An Object Based Approach
Engineering Problem Solving with C++ An Object Based Approach
Capitolo 1 – Introduction C++ Programming
COMS 261 Computer Science I
Modifying Objects Assignment operation Assignment conversions
The Fundamentals of C++
Presentation transcript:

C++ Program Design An Introduction to Programming and Object-Oriented Design

A Rich History MS-DOS BASIC Windows Visual BASIC IE, IIS Visual Studio 1995 Internet 1990 GUI 1981 PC 2002 XML Web Services

Rapidly Changing Technology Computational power CPU power doubling every 18 months Graphics 5x per year Storage 2x per year Networking 4x per year New devices Mobile screens, cameras, Tablet PC, Pocket PCs, mobile phones Connectivity Wireless High-speed Internet

Chap. 2 C++: The fundamentals function main() include comments definitions simple interactive input and output integer, floating- point, and character types integer, floating- point, and character literals Key Concepts C++ names declarations expressions usual unary conversions usual binary conversions operator precedence operator associativity iostream insertion and extraction

A FIRST PROGRAM // Program 2.1: Display greetings // Author: Bryan Zeng // Date: 7/24/2002 #include using namespace std; int main() { cout << "Hello world!" << endl; return 0; } Processed by the preprocessor operand insertion operator

程序运行的结果 name of the program output of the program

A SECOND PROGRAM #include using namespace std; int main() { // Input price cout << "Purchase price ? "; float Price; cin >> Price; // Compute and output sales tax cout << "Sales tax on $" << Price << " is "; cout << "$" << Price * 0.04 << endl; return 0; } extraction operator insertion operator

Screen capture

ASSIGNING A VALUE x y What are we going to do? x-coordinate y-coordinate

ASSIGNING A VALUE #include using namespace std; int main() { // Input line s parameters cout << "Slope of line (integer)? "; int m; // Line slope cin >> m; cout << "Intercept of y-axis (integer)? "; int b; // y-intercept cin >> b;

ASSIGNING A VALUE // Input x-coordinate of interest cout << "x-coordinate of interest (integer)? "; int x; // x-coordinate of interest cin >> x; // compute and display y-coordinate int y; y = m * x + b; cout << "y = " << y << " when m = " << m << ";"; cout << " b = " << b << "; x = " << x << endl; return 0; }

Screen capture

FUNDAMENTAL C++ OBJECTS the integer objects the floating-point objects the character objects

Integer object types short (16 bits) int (32 bits) long (32 bits) the size of int is implementation dependent

Character object types Characters are encoded using some scheme where an integer represents a particular character. Foe example, the integer 98 might represent the letter a. ‘a’ < ‘b’ < ‘c’ < … < ‘z’ ‘0’ < ‘1’ < ‘2’ < … < ‘9’ The operators defined on the integer types are defined on the character types as well. ‘A’ + 1 gives ‘B’ ‘J’ + 3 results in ‘M’

Floating-point object types float (32 bits) double (64 bits) long double (80 bits)

CONSTANTS String and character constants Integer constants Floating-point constants

String and character constants “Hello World!” “Hello World!\n” (“Hello World!\012”) “\“Hello World!\”” Memory allocation for a string literal HelloWorld! ……………………

Integer constants L 45L 101L 55L L base 8 numbers not valid constants 0x2a 0x45 0xffL 0xA1e base 16 numbers

Example of constants #include using namespace std; int main() { cout << "Display integer constants\n" << endl; cout << "Octal 023 is " << 023 << " decimal" << endl; cout << "Decimal const 23 is " << 23 << " decimal" << endl; cout << "Hex const 0x23 is " << 0x23 << " decimal" << endl; return 0; }

Screen capture

Floating-point constants L 45.e E-4

Example #include using namespace std; int main() { cout << 230.e+3 << endl; cout << 230E3 << endl; cout << << endl; cout << 2.3E5 << endl; cout << 0.23e6 << endl; cout <<.23E+6 << endl; return 0; }

NAMES Keywords (reserved words) Identifiers: a name defined by and given meaning to by the programmer.

Some of the keywords asmelsefloatoperator autoenumforprivate boolexplicitfriendthrow breakexterngototrue casefalseinlinetypedef

Examples of identifiers WordCount Time NumberOfStudents

DEFINITIONS int x; int WordCnt, Radius, Height; float FlightTime, Mileage, Speed;

Examples of definitions #include using namespace std; int main() { float f; int i; char c; double d; cout << "f's value is " << f << endl; cout << "i's value is " << i << endl; cout << "c's value is " << c << endl; cout << "d's value is " << d << endl; return 0; }

Initial values always give objects an initial value!

CASE STUDY COMPUTING AVERAGE VELOCITY input: start and end milepost, elapsed time (h/m/s) output: average velocity (miles per hour).

CASE STUDY Step 1. Issue the prompts and read the input. Step 2. Compute the elapsed time in hours. Step 3. Compute the distance traveled. Step 4. Compute the averaged velocity. The steps to solving the problem:

#include using namespace std; int main() { cout << "All inputs are integers!\n"; cout << "Start milepost? "; int StartMilePost; cin >> StartMilePost; cout << "End time (hours minutes seconds)? "; int EndHour, EndMinute, EndSecond; cin >> EndHour >> EndMinute >> EndSecond; cout << "End milepost? "; int EndMilePost; cin >> EndMilePost;

float ElapsedTime = EndHour + (EndMinute / 60.0) + (EndSecond / ); int Distance = EndMilePost - StartMilePost; float Velocity = Distance / ElapsedTime; cout << "\nCar traveled " << Distance << " miles in "; cout << EndHour << " hrs " << EndMinute << " min " << EndSecond << "sec\n"; cout << "Average velocity was " << Velocity << " mph" << endl; return 0; } expressions assignment

CHAPTER 3 Modifying objects assignment operation assignment conversions assignment precedence and associativity strings EzWindows extraction operations const declarations compound assignment operations input with cin increment and decrement operation

Assignment int Score1 = 90; int Score2 = 75; int temp = Score2; Score2 = Score1; Score1 = temp; Score1Score2 temp to swap the values of Score1 and Score2

Assignment conversions int x = 0; x = 3.9; short s1 = 0; long i2 = 65535; s1 = i2; short m1 = 0; long n2 = 65536; m1 = n2; cout << x << s1 << m1 3 0

Assignment precedence and associativity x = y = z + 2; x = (y = (z + 2));

compound assignment i = i + 5; i += 5; i = i + 1; i += 1; ++i; i = i - 1; i -= 1; --i;

Increment and Decrement int i = 4; int j = 5; int k = j * ++i; cout << k << i; int i = 4; int j = 5; int k = j * i++; cout << k << i;

The String Class string Message1 = “Enter your password:”; string Message2 = Message1; string FirstName = “Zach”; string LastName = “Davidson”; string FullName = FirstName + “ ” + LastName; FirstName += LastName; string Date = “March 7, 1994”; int length = Date.size();

case study converting dates from American format to international format December 29, December 1953 MonthDayYear Day Month Year

solution // Prompt for and read the date cout << “Enter the date in American format ” << “(e.g., December 29, 1953): ”; char buffer[100]; cin.getline(buffer, 100); string Date = buffer;

solution to extract the month: int i = Date.find(“ ”); string Month = Date.substr(0, i); December 29, 1953

solution to locate and extract the day: int k = Date.find(“,”); string Day = Date.substr(i+1, k-i-1); December 29, 1953

solution December 29, 1953 to extract the year: string Year = Date.substr( k+2, Date.size() );

solution to display the date in the new format: string NewDate = Day + “ ” + Month + “ ” + Year; cout << “Original date: ” << Date << endl; cout << “Converted date: ” << NewDate << endl;

screen capture

ezwin objects Y-coordinate: Distance from top of screen X-coordinate:Distance from left edge of screen Height of window Width of window

Windows Api Demo // Program 3.6: Api Demo #include using namespace std; int ApiMain() { const int Width = 8; const int Height = 7; int LawnLength = 6; int LawnWidth = 5; int HouseLength = 3; int HouseWidth = 2; Click to view source

SimpleWindow Window(“Api Demo”, Width, Height); Window.Open(); RectangleShape Lawn(Window, Width/2.0, Height/2.0, Green, LawnLength, LawnWidth); Lawn.Draw(); RectangleShape House(Window, Width/2.0, Height/2.0, Yellow, HouseLength, HouseWidth); House.Draw(); cout << "Type a character followed by a\n" << "return to remove the window and exit" << endl; char AnyChar; cin >> AnyChar; Window.Close(); return 0; }

CHAPTER 4 Control constructs bool type Relational operators short-circuit evaluation if-else statement switch statement break statement enum statement for construct while construct do construct infinite loops invariants Key Concepts

A BOOLEAN TYPE bool P = true; bool Q = false; bool R = true; bool S = false; Boolean operators: P; // P has value true P && R; // logical and is true when both operands are true P || Q; // logical or is true when at least one of the operands is true P && S; // logical and is false when at least one of the operands is false !R ; // logical not is false when the operand is true

The logical operators are also defined for the integral type objects such as int and char. int i = 1; int j = 0; int k = -1; int m = 0; i // i is nonzero i && k // both operands are nonzero !j // not is true when operand is zero The following expressions are true. The following expressions evaluate to false. j || m // both operands are zero !k // not is false when the operand is nonzero

Relational operators int i = 1; int j = 2; int k = 2; char c = ‘2’; char d = ‘3’; char e = ‘2’; The following expressions are true. c == e i != k i e j >= k The following expressions are false. i == j c != e j =k

Operator precedence i + l < j * 4 && ! P || Q Operation Unary operators Multiplicative arithmetic Additive arithmetic Relational ordering Relational equality Logical and Logical or Assignment Precedence of selected operators arranged from highest to lowest (((i+1) < (j*4)) && (!P)) || Q

Short-circuit evaluation ( i != 0 ) && ( ( j / i ) > 5 )

Conditional execution using the if-else statement Expression Action 1 Action 2 true false if ( Expression ) Action 1 else Action 2

example cout << "Please enter two numbers: "; int Value1, Value2; cin >> Value1 >> Value2; int Larger; if ( Value1 < Value2 ) Larger = Value2; else Larger = Value1; cout << "The larger of " << Value1 << " and " << Value2 << " is " << Larger << endl;

conditional execution using the switch statement switch (command) { case 'u': cout << "Move up" << endl; break; case 'd': cout << "Move down" << endl; break; case 'l': cout << "Move left" << endl; break; case 'r': cout << "Move right" << endl; break; default: cout << "Invalid command" << endl; }

computing a requested expression view source file case study

Iteration using the while statement Expression Action true false

case study compute average of a list of values Click to view source

Case study: validating a date We next develop a program that prompts a user for a date and then determines whether that date is valid. Please enter a date (mm dd yyyy): Invalid month: 13 Example:

How to determine leap years Years divisible by 4 Years divisible by 100 Years divisible by 400 Shaded areas represent leap years Click to view source

Simple string and character processing Model for text processing // prepare for string processing // extract and process strings while (cin >> s) { // prepare to process string s // process current string s // prepare to process next string } // finish string processing …… Click to view source

case study: A more complicated text processor: click to view source Echo input to standard output, converting uppercase to lowercase.

screen capture

Iteration using the for construct for ( ForInit; ForExpression; PostExpression ) Action Initialization step to prepare for the for loop evaluation Preparation for next iteration of the for loop Logical expression that determines whether the action is to be executed Action to be performed for each iteration of the for loop

example Compute n!: cout << "Please enter a positive integer: "; int n; cin >> n; int nfactorial = 1; for (int i = 2; i <= n; ++i) { nfactorial *= i; } cout << n << "! = " << nfactorial << endl;

CHAPTER 5 Function basics functions value parameters invocation and flow of control header files function prototyping activation records define directives file inclusion conditional compilation iostream functionality pseudorandom numbers iomanip manipulators formatted output fstream class ifstream fstream class ofstream file manipulation stdlib library exit() function assert library translation unit casting Key Concepts

function basics consider the following quadratic expression: the roots of the expression are given by: click to view source

function basics double radical = sqrt(b*b - 4*a*c); function sqrt( ) parameters (arguments) returns a value of type double

interface specification double sqrt(double number); #include math library function interface function type or return type function name header file parameter (formal parameter)

interface specification FunctionType FunctionName ( ParameterList ) Type of value that the function returns Identifier name of function A description of the form the parameters (if any) are to take ParameterDeclaration, …, ParameterDeclaration Description of individual parameters ParameterType ParameterName

Function prototyping int PromptAndExtract(); float CircleArea(float radius); bool IsVowel(char CurrentCharacter); formal parameter

examples cout << sqrt(14) – sqrt(12); double QuarticRoot = sqrt(sqrt(5)); double x = sqrt( ); double y = sqrt(5, 3); invalid invocations of function actual parameter

the fstream library open a file to read data open a file to write data file io click to view an example

random numbers // program 5.6: display pseudorandom numbers #include using namespace std; int main() { srand( (unsigned int) time(0) ); for ( int i=1; i<=5; ++i ) cout << rand() %100 << endl; return 0; }

CHAPTER 6 programmer-defined functions invocation and flow of control parameters prototypes activation records return statement local object scope global objects name reuse implementation file header file standard class ostringstream standard class istringstream class Label Standard Template Library reference parameters constant parameters default parameters function overloading function overload resolution recursion Key Concepts Programmer-defined functions

Function definition syntax A function definition includes both a description of the interface and the statement list that comprises its actions. Click to view an example.

the local scope C++’s scope rules state that a local object can be used only in the block and in the nested blocks of the block in which it has been defined. Click to view examples

Reference parameters Click to view example 1 Click to view example 2

Passing objects by reference Click to view example

Constant parameters Click to view example

Default parameters Click to view example

Function overloading Click to view example

Recursive functions consider the following example: if n = 0 if n ≥ 1 if n = 0 if n > 0 click to view source

CHAPTER 7 The class construct and object-oriented design class construct information hiding encapsulation data members member functions constructors inspectors mutators facilitators const functions access specification: public and private object-oriented analysis and design Key Concepts

programmer-defined types class ClassName { public : // Prototypes for constructors // and public member functions // and declarations for public // data attributes go here. …… private : // Prototypes for private data // members and declarations for // private data attributes go here. …… };

user-defined class in action class RectangleShape { public: RectangleShape(SimpleWindow &Window, float XCoord, float YCoord, color &color, float Width, float Height); void Draw( ); color GetColor( ) const; float GetWidth( ) const; void SetColor(const color &Color); private: float Width; color Color; }; data members (attributes) inspectors mutator facilitator member functions constructor access specifier

user-defined class in action // program 7.1: user-defined class #include SimpleWindow W("MAIN WINDOW", 8.0, 8.0); int ApiMain() { W.Open(); RectangleShape R(W, 4.0, 4.0, Blue, 2.0, 3.0); R.Draw(); return 0; } Click to view Source Instantiation

using the RectangleShape class Click to view source

CHAPTER 8 Implementing abstract data types data abstraction abstract data type rule of minimality principle default constructors copy constructors member assignment inspectors overloading insertion and extraction operators mutators facilitators const member functions destructors auxiliary functions and operators operator overloading reference return pseudorandom number sequence Key Concepts

Rational ADT basics A rational number is the ratio of two integers and is typically represented in the manner a/b. The basic arithmetic operations have the following definitions:

Rational ADT basics After development of ADT Rational, we are able to do: Rational a(1, 2); // a = 1/2 Rational b(2, 3); // b = 2/3 cout << a << “ + ” << b << “ = ” << (a + b) << endl;

Rational ADT basics What we need to do: Construct the rational number with default or particular attributes. Add, subtract, multiply, and divide the rational number to another rational number. Copy the value of the rational number to another rational number. Compare the rational number to another rational number. Display the value of the rational number. Extract the value of the rational number.

// program 8.1: Demonstrate Rational ADT #include #include "rational.h" using namespace std; int main() { Rational r; Rational s; cout << "Enter rational number (a/b): "; cin >> r; cout << "Enter rational number (a/b): "; cin >> s; Rational t(r); Rational Sum = r + s; Rational Product = r * s; cout << r << " + " << s << " = " << Sum << endl; cout << r << " * " << s << " = " << Product << endl; return 0; } copy constructor extraction operation insertion operation arithmetic operation

Rational interface description Click to view source

Implementing the rational class Click to view source

CHAPTER 9 Lists one-dimensional arrays array subscripting arrays as parameters array elements as parameters character strings Standard Template Library (STL) container class vector vector subscripting vector resizing string subscripting iterators iterator dereferencing vector of vectors table matrices member initialization list multidimensional arrays Key Concepts

one-dimensional arrays BaseType ID [ SizeExp ] ; Type of Values in list Name of list Bracketed constant expression indicating number of elements in list

one-dimensional array examples const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000; int A[10]; char B[MaxStringSize]; float C[M*N]; int Values[MaxListSize]; see examples

A[0]A[1]A[2]A[3]A[4]A[5]A[6]A[7]A[8]A[9] A (uninitialized) one-dimensional array examples

int i = 7; int j = 2; int k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3; A[j+1] = A[i] + A[0]; A[A[j]] = 12; A[0]A[1]A[2]A[3]A[4]A[5]A[6]A[7]A[8]A[9]

Array initialization int Frequency[5] = {0, 0, 0, 0, 0}; int Total[5] = {0}; int Sub[5]({0, 0, 0, 0, 0}); int Count[5]({0}); int Digits[] = {0, 1, 3, 4, 5, 6, 7, 8, 9}; int Zero[] = {0}; char Alphabet[] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’}; Rational R[10];

Note Arrays defined in the global scope with fundamental base types have their array elements set to 0 unless there is explicit initialization. Arrays defined in a local scope with fundamental base types have uninitialized array elements unless there is explicit initialization.

Character string arrays char Letters[] = “abcdefghijklmnopqrstuvwxyz”; char G [] = “Hello”; ‘H’‘e’‘l’ ‘o’‘\0’ G[0]G[1]G[2]G[3]G[4]G[5] G “null character”

case study Display inputs in reverse order. (Click here to view source)

restrictions on the use of arrays a function return type cannot be an array; an array connot be passed by value; an array cannot be the target of an assignment; the size of the array must be a compile-time constant; an array cannot be resized.

container classes Standard Template Library (STL) deque list priority_queue queue stack vector map set container adapters

class vector The vector class template provides four constructors for defining a list of elements: a default constructor to define an empty list. a copy constructor to make a copy of an existing list. a constructor with a parameter that specifies the initial size of the list, the elements are initialized using the default constructor of the list element type. a constructor with two parameters, the first parameter specifies the initial size of the list, the second parameter specifies the initial value of each list element.

case study const int N = 20; const int M = 40; cout << “Size of list to produce: ”; int length; cin >> length; Rational r(1, 2); vector A(10); vector B(M); vector C(M*N); vector D(length); vector E(N); vector F(N, r); vector G(10, 1); vector H(M, ‘h’); vector I(M*N, 0); vector J(length, 2);

vector copy and assignment vector R(E); vector S(G); vector T(J); vector U(10, 4); vector V(5, 1);

U V U V V = U; The assignment operator = is a member operator of the vector class

Randomly accessing a vector’s elements The principal random access methods are overloading of the subscript operator []. A[0] = 57; cout << A[5];

Sequential access methods restrictions: bidirectional unidirectional The vector sequential access methods are implemented using iterators sentinel vector A(5); …… vector ::iterator q ++q; --q;

A A.begin() A.end() A.rend() A.rbegin()

vector List(5); for (int i = 0; i < List.size(); ++i) { List[i] = i; } typedef vector ::iterator iterator; typedef vector ::reverse_iterator reverse_iterator; List

iterator p = List.begin(); cout << *p << “ ”; ++p; cout << *p << “ ”; ++p; cout << *p << “ ”; --p; cout << *p << “ ”; List iterator q = List.rbegin(); cout << *q << “ ”; ++q; cout << *q << “ ”; ++q; cout << *q << “ ”; --q; cout << *q << “ ”;

int Sum = 0; for (iterator li = List.begin( ); li != List.end( ); ++li) { Sum = Sum + *li; } a typical use of iterators:

Passing a vector Vector objects can be used like objects of other types. void GetList(vector &A) { int n = 0; while (( n > A[n])) { ++n; } A.resize(n); }

void PutList( vector &A ) { for ( int i=0; i<A.size( ); ++i ) { cout << A[i] << endl; } void GetValues(vector &A) { A.resize(0); int Val; while (cin >> Val) { A.push_back(Val); }

String class revisited void GetWords(vector &List) { List.resize(0); string s; while (cin >> s) { List.push_back(s); }

If standard input contained: a list of words to be read. then vector A; GetWords(A); would set A in the manner: A[0]a A[1]list A[2]of A[3]words A[4]to A[5]be A[6]read. The following would be also true: A[0][0] == ‘a’; A[3][2] == ‘r’;

Multidimensional arrays int A[3][3]={1, 2, 3, 4, 5, 6, 7, 8, 9}; int B[3][3]={{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; A[0][0]A[0][1]A[0][2]A[1][0]A[1][1]A[1][2]A[2][0]A[2][1]A[2][2]

void GetWords(char List[][MaxStringSize], int MaxSize, int &n) { for (n=0; (n >List[n]); ++n) { continue; } const int MaxStringSize = 10; const int MaxListSize = 10; char A[MaxListSize][MaxStringSize]; int n; GetWords(A, MaxListSize, n); This would set A in the following manner:

A[0]‘a’‘\0’ A[1]‘l’‘i’‘s’‘t’‘\0’ A[2]‘o’‘f’‘\0’ A[3]‘w’‘o’‘r’‘d’‘s’‘\0’ A[4]‘t’‘o’‘\0’ A[5]‘b’‘e’‘\0’ A[6]‘r’‘e’‘a’‘d’‘.’‘\0’ A[7] A[8] A[9] a list of words to be read. Click here to view source

CHAPTER 11 Pointers and dynamic memory lvalues, rvalues pointer types null address dereferencing operator * indirect member selector operator -> address operator & pointer assignment indirect assignment pointers as parameters pointers to pointers constant pointers member assignment pointers to constants arrays and pointers command-line parameters pointers to function dynamic objects free store operators new and delete exception handling dangling pointers memory leak destructors copy constructor this pointer Key Concepts

Pointer basics int i = 100, *iPtr=0; char c = ‘z’, *s=0; Rational *rPtr=0; iPtr = &i; s = &c; iPtr = i; s = c; indirection (dereferencing) operator address operator illegal statements s c iPtr i ‘z’ 100

int m =0; int n = 1; int* Ptr1 = &m; int *Ptr2 = Ptr1; int *Ptr3 = &n; *Ptr1 = *Ptr3; Ptr2 = Ptr3; Ptr3 Ptr2 Ptr1 1n 0m Ptr3 Ptr2 Ptr1 1n 1m

Rational a(4, 3); Rational *aPtr = &a; (*aPtr).Insert(cout); aPtr->Insert(cout); A pointer object points to class-type objects (the selection operator has higher precedence) indirect member selector operator

Pointers to pointers int **PtrPtr; int i = 100; int *Ptr = &i; PtrPtr = &Ptr; PtrPtr = Ptr; illegal statement 100 PtrPtr Ptr i

Example: pointers can be used to simulate reference parameters Click to view source

Constant pointers and pointers to constants suppose: char c1 = ‘a’; char c2 = ‘b’; const char *Ptr1 = &c1; char const *Ptr2 = &c1; char *const Ptr3 = &c2; *Ptr1 and *Ptr2 are considered to be constants; Ptr1 and Ptr2 are not constant; Ptr3 is a constant; *Ptr3 is not constant read the declarations backwards

character string processing char Text[9] = “Bryan”; for ( char *Ptr=Text; *Ptr!=‘\0’; ++Ptr; ) { cout << Ptr << endl; } Bryan ryan yan an n int strlen(const char s[]) { int i; for (i=0; s[i]!=‘\0’; ++i) { continue; } return i; }

program command-line parameters bcc32 SourceFileName ezWin.lib example: command-line parametersprogram name Click to view source

dynamic objects int i = 100; int *ip; ip = new int(256); Rational *rp, *rlist; rp = new Rational(3, 4); rlist = new Rational[5]; delete ip; delete rp; delete [] rlist; memory leak

Chapter 13 Inheritance is-a relationship has-a relationship uses-a relationship base class derived class public inheritance private inheritance single inheritance multiple inheritance Key Concepts

Object-oriented design using inheritance Writing instruments Lead pencil BallpointRoller ball Fountain Cartridge Reservoir Retractable NonretractableRetractable MechanicalWooden NonretractablePush buttonScrewClicker Pen

Relationships between objects is-a relationship: helps create a hierarchy of abstractions based on inheritance has-a relationship: some object is part of another uses-a relationship: one object uses another object in some way

A hierarchy of shapes C:WindowObject DM:Window, Location MF:GetPosition(), GetWindow(), SetPosition() C:Shape DM:Color MF:GetColor(), SetColor() C:RectangleShape DM:Width, Height MF:Draw(), GetWidth(), GetHeight(), SetSize() C:EllipseShape DM:Width, Height MF:Draw(), GetWidth(), GetHeight(), SetSize() C:Label C: Class DM: Data members MF: Member function is-a

Width Height EllipseShap Width Height RectangleShap Click to view source

Declaring a derived class class DerivedClass : public BaseClass { public: // public section …… private: // private section …… }; Derived class name Access specifier (usually public) Class name of base class

Implementing a derived class DClass::DClass(PList) : BClass(PList), DMbrList { // Body of derived class constructor …… }; Derived class name Derived class constructor parameter list Base class name Base class constructor parameter list Class data member initialization list

Shape::Shape(SimpleWindow &w, const Position &p, const color &c) : WindowObject(w, p), Color(c) { // no code needed! } RectangleShape::RectangleShape(SimpleWindow &Window, const Position &Center, const color &c, float w, float h) : Shape(Window, Center, c), Width(w), Height(h) { // no code needed! } Click to view example

Protected members and inheritance Inheritance Type Base Class MemberDerived Class AccessMember Access public protected privateinaccessible protected publicprotected privateinaccessible private publicprivate protectedprivate inaccessible

examples: class SomeClass { public: void MemberFunction(); int PublicData; protected: int ProtectedData; private: int PrivateData; };

void SomeClass::MemberFunction() { PublicData = 1; // access allowed ProtectedData = 2; // access allowed PrivateData = 3; // access allowed } void NonMemberFunction() { SomeClass C; C.PublicData = 1; // access allowed C.ProtectedData = 2; // illegal C.PrivatedData = 3; // illegal }

class BaseClass { public: int PublicData; protected: int ProtectedData; private: int PrivateData; }; class DerivedClass : public BaseClass { public: void DerivedClassFunction(); private: // Details omitted };

void DerivedClass::DerivedClassFunction() { PublicData = 1; // access allowed ProtectedData = 2; // access allowed PrivatedData = 3; // illegal }

Chapter 14  polymorphism  pure polymorphism  function template  class template  container class  iterator class  friend to a class  virtual function  pure virtual function  abstract base class  virtually derived class Templates and polymorphism

Function templates #include using namespace std; template void f( T i ) { cout << “template f( ): ” << i << endl; } void f( int i ) { cout << “explicit f( ): ” << i << endl; } int main() { f(1.5); f(1); f(‘a’); return 0; } Why function templates? max( ), min( ), ……

Class templates template class Bunch { public: Bunch( ); Bunch(const T &val); Bunch(const T A[n]); int size( ) const {return NumberValues;} const T& operator[ ](int i) const; T& operator[ ](int i); private: T Values[n]; int NumberValues; }; Bunch

Class templates template class Array { public: Array(int n=10, const T &val=T()); Array(const T A[ ], int n); Array(const Array &A); ~Array(); int size() const {return NumberValues;} Array & operator=(const Array ); const T& operator[ ](int i) const; T& operator[ ](int i); private: int NumberValues; T *Values; }; Array

Class templates Bunch A; Bunch B; Array C(10, 1); Array D(20, 2); A = B; C = D;

Polymorphism Click to view source

Abstract base classes A class with a pure virtual function is called an abstract base class. class Shape : pubic WindowObject { public: Shape(simpleWindow &w, const Position &p, const Color c = Red); color GetColor( ) const; void SetColor(const color c); virtual void Draw( ) = 0; private: color Color; }; Shap S; // invalid TriangleShape T(W, P, Red, 1); // valid Shape &R = T;

Virtual multiple inheritance suppose we have the following definitions: class BaseClass { public: int DataValue; }; class DerivedClass1 : public BaseClass { // … }; class DerivedClass2 : public BaseClass { // … };

class MultipleClass1 is derived from both DerivedClass1 and DerivedClass2 : class MultipeClass1 : public DerivedClass1, public DerivedClass2 { // … }; MultipeClass1 A; A.DerivedClass1::DataValue = 100; A.DerivedClass2::DataValue = 200; Click to view complete source

class DerivedClass3 : virtual public BaseClass { // … }; class DerivedClass4 : virtual public BaseClass { // … }; class MultipleClass2 : virtual public DerivedClass3, virtual public DerivedClass4 { // … }; DerivedClass3::DataValue DerivedClass4::DataValue BaseClass::DataValue

CHAPTER 10 application programmer interface graphical user interface event-based programming callbacks mouse events graphical programming timer events bitmaps The EzWindows API: a detailed examination

API

计算机硬件 系统软件(操作系统等) 支撑软件(开发工具等) 基础软件 电子 商务 应用软件 CAD 远程 教育 电子 政务 MIS 软件之间的关系

HardwareHardware OS (Windows) EzWindows API

A Simple Window Class The prototype of the constructor for the SimpleWindow class is: SimpleWindow( const string &WindowTitle = “Untitled”, float Width=8.0, float Height=8.0, const Position &WindowPosition=Position(0.0, 0.0) );

Example SimpleWindow HelloWindow( “Hello EzWindows”, 10.0, 4.0, Position(5.0, 6.0) ); HelloWindow.Open(); assert(HelloWindow.GetStatus() == WindowOpen); To create a window:

Example HelloWindow.RenderText( UpperLeft, LowerRight, “Hello EzWindows”, White, Black ); To display text in the window: text foreground color text background color Click to view source

How EzWindows works?

the Bitmap Class EzWindows provides a facility that enables us to display bitmaps in a window. Click to view source.

MOUSE EVENTS EzWindows also provides a simple facility for using the mouse. The basic idea is that the application tells EzWindows what function to call when a mouse click occurs in an EzWindows SimpleWindow ( this procedure is called registering a callback ).

Registering a callback void SetMouseClickCallback(MouseCallback f); StudyStudy CASE Mouse Clicks

Bitmaps and Mouse Events EzWindows builds in a useful feature that is used to determine whether a location is inside a bitmap. StudyStudy CASE Card Flipping

TIMER EVENTS Timer feature of EzWindows can be used to perform some action at a predetermined time or interval. SetTimerCallback() StartTimer() StopTimer() StudyStudy CASE Click to view source.

ALERT MESSAGES Click to view how to use Message box.