c++ program design an introduction to programming and object-oriented design
TRANSCRIPT
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
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
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
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
程序运行的结果name of the program
output of the program
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
Screen capture
ASSIGNING A VALUE
x
y
What are we going to do?
x-coordinate
y-coordinate
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;
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;
}
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
H e l l o W o r l d ! 0
010
04
0 010
04
1 010
04
2
……………………
01
00
52
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
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;}
Screen capture
Floating-point constants
2.34 3.1415 .21L 45.e+23 2.3E-4
231045 4103.2
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;}
NAMES
• Keywords (reserved words)
• Identifiers: a name defined by and given meaning to by the programmer.
Some of the keywords
asm else float operator
auto enum for private
bool explicit friend throw
break extern goto true
case false inline typedef
Examples of identifiers
WordCount Time NumberOfStudents
DEFINITIONS
int x;
int WordCnt, Radius, Height;
float FlightTime, Mileage, Speed;
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;
}
Initial values
always give objects an initial value!
CASE STUDY
COMPUTING AVERAGE VELOCITY
eElapsedTim
DistanceVelocity
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 <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;
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
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;
90 75
90 75 75
90 90 75
75 90 75S
core1 S
core2
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 -1 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;
25 5 20 5
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 studyconverting dates from American format to international format
December 29, 1953 29 December 1953
Mont
h Da
y Yea
r 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, 1953to 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 objectsY-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 <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
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 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
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
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
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
Action1 Action2
true false
if ( Expression ) Action1 else Action2
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
32 + 104
82773
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): 13 1 2002Invalid 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:
02 cbxax
the roots of the expression are given by:
a
acbb
2
42
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 <cmath> 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 <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;}
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 adescription of the interface and the statementlist that comprises its actions.
Click to view an example.
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
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:
1...)1(
1!
nnn
if n = 0
if n ≥ 1
)!1(
1!
nnn
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 analy
sis 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
mem
ber functions
constructor
access specifier
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
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 e
xtraction operators
• mutators• facilitators• const member functions• destructors• auxiliary functions and oper
ators• operator overloading• reference return• pseudorandom number seq
uence
Key Concepts
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
/
/
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;
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 <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
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
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]
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’ ‘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)
dequelistpriority_queuequeuestackvectormapset
container adapters
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.
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);
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);
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
Randomly accessing a vector’s elements
The principal random access methods areoverloading of the subscript operator [].
A[0] = 57;cout << A[5];
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;
14 723 512 621 114
A
A.begin() A.end()
A.rend() A.rbegin()
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
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
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<int> &A) {int n = 0;while (( n < A.size( )) && (cin >> A[n])) {
++n;}A.resize(n);
}
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);}
}
String class revisited
void GetWords(vector<string> &List) {List.resize(0);string s;while (cin >> s) {
List.push_back(s);}
}
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’;
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]
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:
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
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 statementss
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
100PtrPtr 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
ryanyanann
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 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
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 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
WidthH
eig
ht
EllipseShap
Width
Heig
ht
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 nameDerived classconstructorparameter list
Base class nameBase classconstructorparameter list
Class data memberinitialization 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 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
examples:
class SomeClass {public:
void MemberFunction();int PublicData;
protected:int ProtectedData;
private:int PrivateData;
};
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
}
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 allowedProtectedData = 2; // access allowedPrivatedData = 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
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( ), ……
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>
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>
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;
Polymorphism
Click to view source
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;
Virtual multiple inheritancesuppose we have the following definitions:
class BaseClass {public:
int DataValue;};class DerivedClass1 : public BaseClass {
// …};class DerivedClass2 : public BaseClass {
// …};
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
class DerivedClass3 : virtual public BaseClass {// …
};class DerivedClass4 : virtual public BaseClass {
// …};class MultipleClass2 : virtual public DerivedClass3, virtual public DerivedClass4 {
// …};
DerivedClass3::DataValue
DerivedClass4::DataValueBaseClass::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
软件之间的关系
HardwareHardwareHardwareHardware
OS (Windows)OS (Windows)
EzWindows APIEzWindows 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 colortext 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);
StudyCASE Mouse Clicks
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
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.
ALERT MESSAGES
Click to view how to use Message box.