c++ program design an introduction to programming and object-oriented design

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

Upload: arnold-lee

Post on 17-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

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

C++ Program Design

An Introduction to Programming and Object-Oriented Design

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

A Rich History

MS-DOSBASIC

WindowsVisual BASIC

IE, IISVisual Studio

1995Internet

1990GUI

1981PC

2002XML

Web Services

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

Rapidly Changing TechnologyComputational 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

maryfj
Steve, I checked on this camera and it looks like itis still Sony's top of the line digital video camera. http://www.sonystyle.com/digitalimaging/P_Feature_VX2000.shtml
Page 4: C++ Program Design An Introduction to Programming and Object-Oriented Design

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 ex

traction

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

A FIRST PROGRAM

// Program 2.1: Display greetings// Author: Bryan Zeng// Date: 7/24/2002

#include <iostream>using namespace std;int main() {

cout << "Hello world!" << endl; return 0;}

Processed by the preprocessor

operand

insertion operator

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

程序运行的结果name of the program

output of the program

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

A SECOND PROGRAM

#include <iostream>using namespace std;int main() {

// Input pricecout << "Purchase price ? ";float Price;cin >> Price;// Compute and output sales taxcout << "Sales tax on $" << Price << " is ";cout << "$" << Price * 0.04 << endl;return 0;

}

extraction

operator

insertion operator

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

Screen capture

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

ASSIGNING A VALUE

x

y

What are we going to do?

x-coordinate

y-coordinate

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

ASSIGNING A VALUE

#include <iostream>using namespace std;int main() {

// Input line s parameterscout << "Slope of line (integer)? ";int m; // Line slopecin >> m;cout << "Intercept of y-axis (integer)? ";int b; // y-interceptcin >> b;

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

ASSIGNING A VALUE

// Input x-coordinate of interestcout << "x-coordinate of interest

(integer)? ";int x; // x-coordinate of interestcin >> x;// compute and display y-coordinateint y;y = m * x + b;cout << "y = " << y << " when m = "

<< m << ";";cout << " b = " << b << "; x = " << x

<< endl;return 0;

}

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

Screen capture

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

FUNDAMENTAL C++ OBJECTS

• the integer objects

• the floating-point objects

• the character objects

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

Integer object types

• short (16 bits)

• int (32 bits)

• long (32 bits)

the size of int is implementation dependent

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

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’

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

Floating-point object types

• float (32 bits)

• double (64 bits)

• long double (80 bits)

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

CONSTANTS

• String and character constants

• Integer constants

• Floating-point constants

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

String and character constants

“Hello World!”

“Hello World!\n” (“Hello World!\012”)

“\“Hello World!\””

Memory allocation for a

string literal

H e l l o W o r l d ! 0

010

04

0 010

04

1 010

04

2

……………………

01

00

52

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

Integer constants

23 45 101 55

23L 45L 101L 55L

023 077L 045 010 base 8 numbers

038 093 0779 not valid constants

0x2a 0x45 0xffL 0xA1e base 16 numbers

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

Example of constants

#include <iostream>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;}

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

Screen capture

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

Floating-point constants

2.34 3.1415 .21L 45.e+23 2.3E-4

231045 4103.2

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

Example#include <iostream>using namespace std;int main() {

cout << 230.e+3 << endl;cout << 230E3 << endl;cout << 230000.0 << endl;cout << 2.3E5 << endl;cout << 0.23e6 << endl;cout << .23E+6 << endl;

return 0;}

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

NAMES

• Keywords (reserved words)

• Identifiers: a name defined by and given meaning to by the programmer.

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

Some of the keywords

asm else float operator

auto enum for private

bool explicit friend throw

break extern goto true

case false inline typedef

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

Examples of identifiers

WordCount Time NumberOfStudents

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

DEFINITIONS

int x;

int WordCnt, Radius, Height;

float FlightTime, Mileage, Speed;

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

Examples of definitions#include <iostream>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;

}

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

Initial values

always give objects an initial value!

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

CASE STUDY

COMPUTING AVERAGE VELOCITY

eElapsedTim

DistanceVelocity

input: start and end milepost, elapsed time (h/m/s)

output: average velocity (miles per hour).

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

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:

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

#include <iostream>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;

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

float ElapsedTime = EndHour + (EndMinute / 60.0) + (EndSecond / 3600.0);

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 << " mp

h" << endl;return 0;

}

expressionsassignment

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

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

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

Assignment

int Score1 = 90;

int Score2 = 75;

int temp = Score2;

Score2 = Score1;

Score1 = temp;

90 75

90 75 75

90 90 75

75 90 75S

core1 S

core2

temp

to swap the values of Score1 and Score2

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

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 -1 0

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

Assignment precedence and associativity

x = y = z + 2;

x = (y = (z + 2));

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

compound assignment

i = i + 5;i += 5;

i = i + 1;i += 1;++i;

i = i - 1;i -= 1;--i;

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

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;

25 5 20 5

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

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();

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

case studyconverting dates from American format to international format

December 29, 1953 29 December 1953

Mont

h Da

y Yea

r Day Month Year

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

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;

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

solution

to extract the month:

int i = Date.find(“ ”);

string Month = Date.substr(0, i);

December 29, 1953

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

solution

to locate and extract the day:

int k = Date.find(“,”);

string Day = Date.substr(i+1, k-i-1);

December 29, 1953

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

solution

December 29, 1953to extract the year:

string Year = Date.substr( k+2, Date.size() );

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

solution

to display the date in the new format:

string NewDate = Day + “ ” + Month + “ ” + Year;

cout << “Original date: ” << Date << endl;

cout << “Converted date: ” << NewDate << endl;

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

screen capture

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

ezwin objectsY-coordinate:Distance from top of screen

X-coordinate:Distance from left edge of screen

Height of window

Width of window

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

Windows Api Demo

// Program 3.6: Api Demo#include <iostream>#include <string>#include <rect.h>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

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

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;}

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

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

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

A BOOLEAN TYPEbool 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

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

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 nonzeroi && 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

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

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 < j d > e j >= k

The following expressions are false.

i == j c != e j < k d <= c i>=k

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

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

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

Short-circuit evaluation

( i != 0 ) && ( ( j / i ) > 5 )

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

Conditional execution using the if-else statement

Expression

Action1 Action2

true false

if ( Expression ) Action1 else Action2

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

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;

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

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;

}

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

computing a requested expression

view source file

32 + 104

82773

case study

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

Iteration using the while statement

Expression

Action

true false

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

case study

compute average of a list of values

Click to view source

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

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): 13 1 2002Invalid month: 13

Example:

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

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

Page 65: C++ Program Design An Introduction to Programming and Object-Oriented Design
Page 66: C++ Program Design An Introduction to Programming and Object-Oriented Design

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

Page 67: C++ Program Design An Introduction to Programming and Object-Oriented Design
Page 68: C++ Program Design An Introduction to Programming and Object-Oriented Design

case study:

A more complicated text processor:

click to view source

Echo input to standard output, converting uppercase to lowercase.

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

screen capture

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

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

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

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;

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

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

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

function basics

consider the following quadratic expression:

02 cbxax

the roots of the expression are given by:

a

acbb

2

42

click to view source

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

function basics

double radical = sqrt(b*b - 4*a*c);

function sqrt( )

parameters (arguments)

returns a value of type double

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

interface specification

double sqrt(double number);

#include <cmath> math library

function interface

function type or return type

function name

header file

parameter(formal parameter)

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

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

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

Function prototyping

int PromptAndExtract();

float CircleArea(float radius);

bool IsVowel(char CurrentCharacter);

formal parameter

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

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

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

the fstream library

open a file to read data

open a file to write data

file io

click to view an example

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

random numbers

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

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

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

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

Function definition syntax

A function definition includes both adescription of the interface and the statementlist that comprises its actions.

Click to view an example.

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

the local scope

C++’s scope rules state that a local objectcan be used only in the block and in thenested blocks of the block in which it hasbeen defined.

Click to view examples

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

Reference parameters

Click to view example 1

Click to view example 2

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

Passing objects by reference

Click to view example

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

Constant parameters

Click to view example

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

Default parameters

Click to view example

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

Function overloading

Click to view example

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

Recursive functions

consider the following example:

1...)1(

1!

nnn

if n = 0

if n ≥ 1

)!1(

1!

nnn

if n = 0

if n > 0

click to view source

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

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 analy

sis and design

Key Concepts

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

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.……

};

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

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

mem

ber functions

constructor

access specifier

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

user-defined class in action

// program 7.1: user-defined class#include <rect.h>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

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

using the RectangleShape class

Click to view source

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

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 e

xtraction operators

• mutators• facilitators• const member functions• destructors• auxiliary functions and oper

ators• operator overloading• reference return• pseudorandom number seq

uence

Key Concepts

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

Rational ADT basics

A rational number is the ratio of two integersand is typically represented in the manner a/b.The basic arithmetic operations have the followingdefinitions:

bd

bcad

d

c

b

abd

bcad

d

c

b

a

bc

ad

dc

babd

ac

d

c

b

a

/

/

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

Rational ADT basics

After development of ADT Rational, we areable to do:

Rational a(1, 2); // a = 1/2Rational b(2, 3); // b = 2/3cout << a << “ + ” << b << “ = ” << (a + b) << endl;

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

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.

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

// program 8.1: Demonstrate Rational ADT#include <iostream>#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

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

Rational interface description

Click to view source

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

Implementing the rational class

Click to view source

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

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

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

one-dimensional arrays

BaseType ID [ SizeExp ] ;

Type of Values in list

Name of list

Bracketed constant expression indicating

number of elements in list

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

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

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

- - - - - - - - - -

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

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

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;

1 - 8 6 3 - - 5 12 -

A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]

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

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];

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

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.

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

Character string arrays

char Letters[] = “abcdefghijklmnopqrstuvwxyz”;char G [] = “Hello”;

‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’

G[0] G[1] G[2] G[3] G[4] G[5]

G

“null character”

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

case study

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

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

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.

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

container classes

Standard Template Library (STL)

dequelistpriority_queuequeuestackvectormapset

container adapters

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

class vectorThe 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.

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

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<int> A(10);vector<char> B(M);vector <float> C(M*N);vector<int> D(length);vector<Rational> E(N);

vector<Rational> F(N, r);vector<int> G(10, 1);vector<char> H(M, ‘h’);vector<float> I(M*N, 0);vector<int> J(length, 2);

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

vector copy and assignment

vector<Rational> R(E);vector<int> S(G);vector<int> T(J);vector<int> U(10, 4);vector<int> V(5, 1);

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

4 4 4 4 4 4 4 4 4 4

4 4 4 4 4 4 4 4 4 4

1 1 1 1 1

4 4 4 4 4 4 4 4 4 4

U

V

U

V

V = U;

The assignment operator = is a member operator of the vector class

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

Randomly accessing a vector’s elements

The principal random access methods areoverloading of the subscript operator [].

A[0] = 57;cout << A[5];

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

Sequential access methods

restrictions: bidirectional unidirectional

The vector sequential access methods areimplemented using iterators.

14 723 512 621 114

sentinelvector<int>A(5);……

vector<int>::iterator q++q;--q;

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

14 723 512 621 114

A

A.begin() A.end()

A.rend() A.rbegin()

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

vector<int> List(5);for (int i = 0; i < List.size(); ++i) { List[i] = 100 + i;}

100 101 102 103 104

typedef vector<int>::iterator iterator;typedef vector<int>::reverse_iterator reverse_iterator;

List

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

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

100 101 102 101

100 101 102 103 104List

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

104 103 102 103

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

int Sum = 0;for (iterator li = List.begin( ); li != List.end( ); ++li) { Sum = Sum + *li;}

a typical use of iterators:

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

Passing a vector

Vector objects can be used like objects of other types.

void GetList(vector<int> &A) {int n = 0;while (( n < A.size( )) && (cin >> A[n])) {

++n;}A.resize(n);

}

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

void PutList( vector<int> &A ) {for ( int i=0; i<A.size( ); ++i ) {

cout << A[i] << endl;}

}void GetValues(vector<int> &A) {

A.resize(0);int Val;while (cin >> Val) {

A.push_back(Val);}

}

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

String class revisited

void GetWords(vector<string> &List) {List.resize(0);string s;while (cin >> s) {

List.push_back(s);}

}

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

If standard input contained:

a list of wordsto be read.

then

vector<string> 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’;

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

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}};

1 2 3 4 5 6 7 8 9A[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]

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

void GetWords(char List[][MaxStringSize], int MaxSize, int &n) {

for (n=0; (n<MaxSize) && (cin>>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:

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

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 wordsto be read.

Click here to view source

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

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

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

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 statementss

c

iPtr

i

‘z’

100

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

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

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

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

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

Pointers to pointers

int **PtrPtr;int i = 100;int *Ptr = &i;

PtrPtr = &Ptr;

PtrPtr = Ptr; illegal statement

100PtrPtr Ptr i

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

Example: pointers can be used to simulate reference parameters

Click to view source

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

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

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

character string processing

char Text[9] = “Bryan”;for ( char *Ptr=Text; *Ptr!=‘\0’; ++Ptr; ) {

cout << Ptr << endl;} Bryan

ryanyanann

int strlen(const char s[]) {int i;for (i=0; s[i]!=‘\0’; ++i) {

continue;}return i;

}

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

program command-line parameters

bcc32 SourceFileName ezWin.lib

example:

command-line parametersprogram name

Click to view source

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

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

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

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

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

Object-oriented design using inheritanceWriting instruments

Lead pencil

Ballpoint Roller ball Fountain

Cartridg

e Reservoi

r Retractabl

e Nonretractabl

e Retractabl

e

Mechanical Wooden

Nonretractabl

e Push

button

Scre

w Clicke

rPen

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

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

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

A hierarchy of shapesC:WindowObject

DM:Window, LocationMF:GetPosition(), GetWindow(), SetPosition()

C:ShapeDM:ColorMF:GetColor(), SetColor()

C:RectangleShapeDM:Width, HeightMF:Draw(), GetWidth(), GetHeight(), SetSize()

C:EllipseShapeDM:Width, HeightMF:Draw(), GetWidth(), GetHeight(), SetSize()

C:Label

C: ClassDM: Data membersMF: Member function

is-a

is-a is-a

is-a

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

WidthH

eig

ht

EllipseShap

Width

Heig

ht

RectangleShap

Click to view source

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

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

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

Implementing a derived class

DClass::DClass(PList) : BClass(PList), DMbrList { // Body of derived class constructor ……};

Derived class nameDerived classconstructorparameter list

Base class nameBase classconstructorparameter list

Class data memberinitialization list

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

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

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

Protected members and inheritance

Inheritance TypeBase Class Member Derived Class

Access Member Access

public

public public

protected protected

private inaccessible

protected

public protected

protected protected

private inaccessible

private

public private

protected private

private inaccessible

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

examples:

class SomeClass {public:

void MemberFunction();int PublicData;

protected:int ProtectedData;

private:int PrivateData;

};

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

void SomeClass::MemberFunction() {PublicData = 1; // access allowedProtectedData = 2; // access allowedPrivateData = 3; // access allowed

}void NonMemberFunction() {

SomeClass C;C.PublicData = 1; // access allowedC.ProtectedData = 2; // illegalC.PrivatedData = 3; // illegal

}

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

class BaseClass {public:

int PublicData;protected:

int ProtectedData;private:

int PrivateData;};class DerivedClass : public BaseClass {

public:void DerivedClassFunction();

private:// Details omitted

};

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

void DerivedClass::DerivedClassFunction() {PublicData = 1; // access allowedProtectedData = 2; // access allowedPrivatedData = 3; // illegal

}

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

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

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

Fun

ctio

n te

mpl

ates

#include <iostream>using namespace std;template<class T> 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( ), ……

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

Cla

ss te

mpl

ates

template<class T, int n> 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<T, n>

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

Cla

ss te

mpl

ates

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

Array<T>

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

Cla

ss te

mpl

ates

Bunch<int, 10> A;Bunch<int, 20> B;

Array<int> C(10, 1);Array<float> D(20, 2);

A = B;

C = D;

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

Polymorphism

Click to view source

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

Abstract base classesA class with a pure virtual function is calledan 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; // invalidTriangleShape T(W, P, Red, 1); // validShape &R = T;

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

Virtual multiple inheritancesuppose we have the following definitions:

class BaseClass {public:

int DataValue;};class DerivedClass1 : public BaseClass {

// …};class DerivedClass2 : public BaseClass {

// …};

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

class MultipleClass1 is derived from bothDerivedClass1 and DerivedClass2:

class MultipeClass1 : public DerivedClass1, public DerivedClass2 { // …};

MultipeClass1 A;A.DerivedClass1::DataValue = 100;A.DerivedClass2::DataValue = 200;

Click to view complete source

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

class DerivedClass3 : virtual public BaseClass {// …

};class DerivedClass4 : virtual public BaseClass {

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

// …};

DerivedClass3::DataValue

DerivedClass4::DataValueBaseClass::DataValue

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

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

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

API

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

计算机硬件系统软件(操作系统等)支撑软件(开发工具等)

基础软件

电子商务应用软件 CAD

远程教育

电子政务

MIS

软件之间的关系

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

HardwareHardwareHardwareHardware

OS (Windows)OS (Windows)

EzWindows APIEzWindows API

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

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) );

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

Example

SimpleWindow HelloWindow( “Hello EzWindows”, 10.0, 4.0, Position(5.0, 6.0) );

HelloWindow.Open();

assert(HelloWindow.GetStatus() == WindowOpen);

To create a window:

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

Example

HelloWindow.RenderText( UpperLeft, LowerRight, “Hello EzWindows”, White, Black );

To display text in the window:

text foreground colortext background color

Click to view source

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

How EzWindows works?

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

the Bitmap Class

EzWindows provides a facility that enables us to display bitmaps in a window.

Click to view source.

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

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 ).

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

Registering a callback

void SetMouseClickCallback(MouseCallback f);

StudyCASE Mouse Clicks

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

Bitmaps and Mouse Events

EzWindows builds in a useful feature that is used to determine whether a location is inside a bitmap.

StudyCASE

Card Flipping

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

TIMER EVENTS

Timer feature of EzWindows can be used to perform some action at a predetermined time or interval.

SetTimerCallback()

StartTimer()

StopTimer()

StudyCASE Click to view source.

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

ALERT MESSAGES

Click to view how to use Message box.

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