Download presentation
Presentation is loading. Please wait.
Published byArnold Lee Modified over 9 years ago
1
C++ Program Design An Introduction to Programming and Object-Oriented Design
2
A Rich History MS-DOS BASIC Windows Visual BASIC IE, IIS Visual Studio 1995 Internet 1990 GUI 1981 PC 2002 XML Web Services
3
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
4
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
5
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
6
程序运行的结果 name of the program output of the program
7
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
8
Screen capture
9
ASSIGNING A VALUE x y What are we going to do? x-coordinate y-coordinate
10
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;
11
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; }
12
Screen capture
13
FUNDAMENTAL C++ OBJECTS the integer objects the floating-point objects the character objects
14
Integer object types short (16 bits) int (32 bits) long (32 bits) the size of int is implementation dependent
15
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’
16
Floating-point object types float (32 bits) double (64 bits) long double (80 bits)
17
CONSTANTS String and character constants Integer constants Floating-point constants
18
String and character constants “Hello World!” “Hello World!\n” (“Hello World!\012”) “\“Hello World!\”” Memory allocation for a string literal HelloWorld!0 010040 010041 010042 …………………… 010052
19
Integer constants 23 45 101 55 23L 45L 101L 55L 023 077L 045 010base 8 numbers 038 093 0779not valid constants 0x2a 0x45 0xffL 0xA1e base 16 numbers
20
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; }
21
Screen capture
22
Floating-point constants 2.34 3.1415.21L 45.e+23 2.3E-4
23
Example #include 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; }
24
NAMES Keywords (reserved words) Identifiers: a name defined by and given meaning to by the programmer.
25
Some of the keywords asmelsefloatoperator autoenumforprivate boolexplicitfriendthrow breakexterngototrue casefalseinlinetypedef
26
Examples of identifiers WordCount Time NumberOfStudents
27
DEFINITIONS int x; int WordCnt, Radius, Height; float FlightTime, Mileage, Speed;
28
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; }
29
Initial values always give objects an initial value!
30
CASE STUDY COMPUTING AVERAGE VELOCITY input: start and end milepost, elapsed time (h/m/s) output: average velocity (miles per hour).
31
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:
32
#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;
33
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 << " mph" << endl; return 0; } expressions assignment
34
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
35
Assignment int Score1 = 90; int Score2 = 75; int temp = Score2; Score2 = Score1; Score1 = temp; 9075 9075 90 75 9075 Score1Score2 temp to swap the values of Score1 and Score2
36
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
37
Assignment precedence and associativity x = y = z + 2; x = (y = (z + 2));
38
compound assignment i = i + 5; i += 5; i = i + 1; i += 1; ++i; i = i - 1; i -= 1; --i;
39
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 520 5
40
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();
41
case study converting dates from American format to international format December 29, 195329 December 1953 MonthDayYear Day Month Year
42
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;
43
solution to extract the month: int i = Date.find(“ ”); string Month = Date.substr(0, i); December 29, 1953
44
solution to locate and extract the day: int k = Date.find(“,”); string Day = Date.substr(i+1, k-i-1); December 29, 1953
45
solution December 29, 1953 to extract the year: string Year = Date.substr( k+2, Date.size() );
46
solution to display the date in the new format: string NewDate = Day + “ ” + Month + “ ” + Year; cout << “Original date: ” << Date << endl; cout << “Converted date: ” << NewDate << endl;
47
screen capture
48
ezwin objects Y-coordinate: Distance from top of screen X-coordinate:Distance from left edge of screen Height of window Width of window
49
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
50
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; }
51
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
52
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
53
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
54
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
55
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
56
Short-circuit evaluation ( i != 0 ) && ( ( j / i ) > 5 )
57
Conditional execution using the if-else statement Expression Action 1 Action 2 true false if ( Expression ) Action 1 else Action 2
58
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;
59
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; }
60
computing a requested expression view source file 32 + 104 case study
61
Iteration using the while statement Expression Action true false
62
case study compute average of a list of values Click to view source
63
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 2002 Invalid month: 13 Example:
64
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
66
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
68
case study: A more complicated text processor: click to view source Echo input to standard output, converting uppercase to lowercase.
69
screen capture
70
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
71
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;
72
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
73
function basics consider the following quadratic expression: the roots of the expression are given by: click to view source
74
function basics double radical = sqrt(b*b - 4*a*c); function sqrt( ) parameters (arguments) returns a value of type double
75
interface specification double sqrt(double number); #include math library function interface function type or return type function name header file parameter (formal parameter)
76
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
77
Function prototyping int PromptAndExtract(); float CircleArea(float radius); bool IsVowel(char CurrentCharacter); formal parameter
78
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
79
the fstream library open a file to read data open a file to write data file io click to view an example
80
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; }
81
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
82
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.
83
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
84
Reference parameters Click to view example 1 Click to view example 2
85
Passing objects by reference Click to view example
86
Constant parameters Click to view example
87
Default parameters Click to view example
88
Function overloading Click to view example
89
Recursive functions consider the following example: if n = 0 if n ≥ 1 if n = 0 if n > 0 click to view source
90
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
91
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. …… };
92
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
93
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
94
using the RectangleShape class Click to view source
95
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
96
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:
97
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;
98
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.
99
// 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
100
Rational interface description Click to view source
101
Implementing the rational class Click to view source
102
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
103
one-dimensional arrays BaseType ID [ SizeExp ] ; Type of Values in list Name of list Bracketed constant expression indicating number of elements in list
104
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
105
---------- 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
106
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-863--512- A[0]A[1]A[2]A[3]A[4]A[5]A[6]A[7]A[8]A[9]
107
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];
108
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.
109
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”
110
case study Display inputs in reverse order. (Click here to view source)
111
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.
112
container classes Standard Template Library (STL) deque list priority_queue queue stack vector map set container adapters
113
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.
114
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);
115
vector copy and assignment vector R(E); vector S(G); vector T(J); vector U(10, 4); vector V(5, 1);
116
4444444444 4444444444 11111 4444444444 U V U V V = U; The assignment operator = is a member operator of the vector class
117
Randomly accessing a vector’s elements The principal random access methods are overloading of the subscript operator []. A[0] = 57; cout << A[5];
118
Sequential access methods restrictions: bidirectional unidirectional The vector sequential access methods are implemented using iterators. 14723512621114 sentinel vector A(5); …… vector ::iterator q ++q; --q;
119
14723512621114 A A.begin() A.end() A.rend() A.rbegin()
120
vector List(5); for (int i = 0; i < List.size(); ++i) { List[i] = 100 + i; } 100101102103104 typedef vector ::iterator iterator; typedef vector ::reverse_iterator reverse_iterator; List
121
iterator p = List.begin(); cout << *p << “ ”; ++p; cout << *p << “ ”; ++p; cout << *p << “ ”; --p; cout << *p << “ ”; 100 101 102 101 100101102103104 List iterator q = List.rbegin(); cout << *q << “ ”; ++q; cout << *q << “ ”; ++q; cout << *q << “ ”; --q; cout << *q << “ ”; 104 103 102 103
122
int Sum = 0; for (iterator li = List.begin( ); li != List.end( ); ++li) { Sum = Sum + *li; } a typical use of iterators:
123
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); }
124
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); }
125
String class revisited void GetWords(vector &List) { List.resize(0); string s; while (cin >> s) { List.push_back(s); }
126
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’;
127
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}}; 123456789 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]
128
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:
129
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
130
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
131
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
132
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
133
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
134
Pointers to pointers int **PtrPtr; int i = 100; int *Ptr = &i; PtrPtr = &Ptr; PtrPtr = Ptr; illegal statement 100 PtrPtr Ptr i
135
Example: pointers can be used to simulate reference parameters Click to view source
136
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
137
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; }
138
program command-line parameters bcc32 SourceFileName ezWin.lib example: command-line parametersprogram name Click to view source
139
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
140
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
141
Object-oriented design using inheritance Writing instruments Lead pencil BallpointRoller ball Fountain Cartridge Reservoir Retractable NonretractableRetractable MechanicalWooden NonretractablePush buttonScrewClicker Pen
142
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
143
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
144
Width Height EllipseShap Width Height RectangleShap Click to view source
145
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
146
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
147
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
148
Protected members and inheritance Inheritance Type Base Class MemberDerived Class AccessMember Access public protected privateinaccessible protected publicprotected privateinaccessible private publicprivate protectedprivate inaccessible
149
examples: class SomeClass { public: void MemberFunction(); int PublicData; protected: int ProtectedData; private: int PrivateData; };
150
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 }
151
class BaseClass { public: int PublicData; protected: int ProtectedData; private: int PrivateData; }; class DerivedClass : public BaseClass { public: void DerivedClassFunction(); private: // Details omitted };
152
void DerivedClass::DerivedClassFunction() { PublicData = 1; // access allowed ProtectedData = 2; // access allowed PrivatedData = 3; // illegal }
153
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
154
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( ), ……
155
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
156
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
157
Class templates Bunch A; Bunch B; Array C(10, 1); Array D(20, 2); A = B; C = D;
158
Polymorphism Click to view source
159
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;
160
Virtual multiple inheritance suppose we have the following definitions: class BaseClass { public: int DataValue; }; class DerivedClass1 : public BaseClass { // … }; class DerivedClass2 : public BaseClass { // … };
161
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
162
class DerivedClass3 : virtual public BaseClass { // … }; class DerivedClass4 : virtual public BaseClass { // … }; class MultipleClass2 : virtual public DerivedClass3, virtual public DerivedClass4 { // … }; DerivedClass3::DataValue DerivedClass4::DataValue BaseClass::DataValue
163
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
164
API
165
计算机硬件 系统软件(操作系统等) 支撑软件(开发工具等) 基础软件 电子 商务 应用软件 CAD 远程 教育 电子 政务 MIS 软件之间的关系
166
HardwareHardware OS (Windows) EzWindows API
167
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) );
168
Example SimpleWindow HelloWindow( “Hello EzWindows”, 10.0, 4.0, Position(5.0, 6.0) ); HelloWindow.Open(); assert(HelloWindow.GetStatus() == WindowOpen); To create a window:
169
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
170
How EzWindows works?
171
the Bitmap Class EzWindows provides a facility that enables us to display bitmaps in a window. Click to view source.
172
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 ).
173
Registering a callback void SetMouseClickCallback(MouseCallback f); StudyStudy CASE Mouse Clicks
174
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
175
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.
176
ALERT MESSAGES Click to view how to use Message box.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.