Professional Documents
Culture Documents
Chapter06 ADTs
Chapter06 ADTs
Chng 6.
6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 6.10 6.11 6.12 6.13 6.14 6.15
Gii thiu Cu trc - struct Truy nhp cc thnh vin ca struct Ci t kiu d liu ngi dng Time bng struct Ci t mt kiu d liu tru tng Time bng mt lp - class Phm vi lp v truy nhp cc thnh vin ca lp Tch giao din ra khi ci t Qun l quyn truy nhp thnh vin Cc hm truy nhp v cc hm tin ch Khi to cc i tng: Constructor S dng cc i s mc nh cho Constructor Destructor - hm hy Khi no Constructor v Destructor c gi S dng cc hm Set v Get Php gn i tng mc nh
Chng 6.
Ti liu c thm Day 6. TY21 (lp trnh c bn) Chap 4,5. Introduction to OOP Using C++ (IOOP) (khi nim hng i tng)
Chng 6.
6.1 Gii thiu cc kiu d liu phc hp cu to t cc thnh phn thuc cc kiu d liu khc
to kiu d liu mi - kiu d liu ngi dng t nh ngha (user-defined data type)
bn ghi
gm nhiu trng, mi trng lu tr mt thnh vin d liu thuc mt kiu d liu ci sn hoc mt kiu d liu ngi dng khc.
v d
Thi gian(gi, pht, giy) H tn (h, m, tn) 17:10:02, 04:23:12,... (Nguyn, Vn, An), (L, Th, Bnh),...
Chng 6.
Chng 6.
quy tc t tn cho cc thnh vin ca cu trc trong cng struct: khng th trng tn trong cc struct khc nhau: c th trng tn nh ngha struct phi kt thc bng du chm phy.
Cc bin kiu cu trc c khai bo nh cc bin thuc cc loi khc V d: khai bo bin n, mng, con tr, tham chiu...
Time Time Time Time timeObject; timeArray[ 10 ]; *timePtr; &timeRef = timeObject;
Chng 6.
Chng 6.
6.3 Truy nhp cc thnh vin ca struct cc ton t truy nhp thnh vin (member access operator)
Ton t du chm (.) truy nhp trc tip n cc thnh vin ca cu trc/lp Ton t mi tn (->) truy nhp cc thnh vin qua con tr n i tng V d: in thnh vin hour ca i tng timeObject: cout << timeObject.hour;
hoc timePtr = &timeObject; cout << timePtr->hour;
Chng 6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Fig. 6.1: fig06_01.cpp // Create a structure, set its members, and print it. #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setfill; using std::setw; // structure definition struct Time { int hour; // 0-23 (24-hour clock format) int minute; // 0-59 int second; // 0-59 }; // end struct Time void printUniversal( const Time & ); void printStandard( const Time & ); // prototype // prototype
fig06_01.cpp (1 of 3)
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
cout << "Dinner will be held at "; printUniversal( dinnerTime ); cout << " universal time,\nwhich is "; printStandard( dinnerTime ); cout << " standard time.\n"; dinnerTime.hour = 29; dinnerTime.minute = 73;
cout << "\nTime with invalid values: "; printUniversal( dinnerTime ); cout << endl; return 0; } // end main
2004 Trn Minh Chu. FOTECH. VNU.
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
// print time in universal-time format void printUniversal( const Time &t ) { cout << setfill( '0' ) << setw( 2 ) << t.hour << ":" << setw( 2 ) << t.minute << ":" << setw( 2 ) << t.second; } // end function printUniversal
11
// print time in standard-time format Dng du chm truy nhp void printStandard( const Time &t ) cc thnh vin d liu. { cout << ( ( t.hour == 0 || t.hour == 12 ) ? 12 : t.hour % 12 ) << ":" << setfill( '0' ) << setw( 2 ) << t.minute << ":" << setw( 2 ) << t.second << ( t.hour < 12 ? " AM" : " PM" ); } // end function printStandard
Dinner will be held at 18:30:00 universal time, which is 6:30:00 PM standard time. Time with invalid values: 29:73:00 2004 Trn Minh Chu. FOTECH. VNU.
6.4 Ci t kiu d liu ngi dng Time bng struct Truyn tham s:
Mc nh struct c truyn bng gi tr Nn truyn struct bng tham chiu trnh c vic phi sao chp cu trc
12
Chng 6.
13
khng th in ra nh l mt bin n
Phi in/nh dng cho tng thnh vin
Chng 6.
14
Chng 6.
Class body bt u bng ngoc m. Class Time definition (1 of 1) Constructor: thnh vin trng tn vi tn class, Time, v khng c gi tr tr v.
15
public: Time(); // constructor void setTime( int, int, int ); // set hour, minute, second void printUniversal(); // print universal-time format void printStandard(); // print standard-time format private: int hour; int minute; int second;
private data member ch c th c truy nhp t cc member function. Definition kt thc bng du chm phy.
6.5 Ci t mt kiu d liu tru tng Time bng mt lp - class Nhn quyn truy nhp Member access specifiers
quy nh quyn truy nhp cc thnh vin ca lp t cc on trnh bn ngoi nh ngha lp
16
public:
thnh vin c th c truy nhp t trong ton b phm vi ca i tng
private:
thnh vin ch c th c truy nhp t cc hm thnh vin ca chnh lp
protected:
dng cho quan h tha k
Chng 6.
6.5 Ci t mt kiu d liu tru tng Time bng mt lp - class Constructor phng thc khi to
hm thnh vin c bit
khi to cc thnh vin d liu trng tn vi tn lp
17
Chng 6.
6.5 Ci t mt kiu d liu tru tng Time bng mt lp - class Destructor phng thc hy
trng tn vi tn lp
bt u bng du (~)
18
khng c tham s ti a 1 destructor, khng th b gi chng dnh cho vic dn dp, chng hn b nh
class Time { public: Time(); ~Time(); }; Time::~Time() { //empty } // end Time destructor
Chng 6.
19
V d:
Tn lp tr thnh tn kiu d liu mi. Time Time Time Time sunset; arrayOfTimes[ 5 ]; *pointerToTime; &dinnerTime = sunset; // // // // object of type Time array of Time objects pointer to a Time object reference to a Time object
Chng 6.
6.5 Ci t mt kiu d liu tru tng Time bng mt lp - class Cc hm thnh vin c nh ngha bn ngoi lp
ton t phm vi (::)
gn tn thnh vin vi tn lp xc nh duy nht cc hm ca mt lp no cc lp khc nhau c th c cc hm thnh vin trng tn
20
6.5 Ci t mt kiu d liu tru tng Time bng mt lp - class Cc hm thnh vin c nh ngha bn trong lp
Khng cn ton t phm vi (::) v tn lp Trnh bin dch s chuyn thnh hm inline nu c th
Bn ngoi lp, cc hm inline cn t kho inline
21
Chng 6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Fig. 6.3: fig06_03.cpp // Time class. #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setfill; using std::setw; // Time abstract data type (ADT) definition class Time {
22
fig06_03.cpp (1 of 5)
nh ngha lp Time.
public: Time(); // constructor void setTime( int, int, int ); // set hour, minute, second void printUniversal(); // print universal-time format void printStandard(); // print standard-time format
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
fig06_03.cpp (2 of 5)
}; // end class Time // Time constructor initializes each data member to zero and // ensures all Time objects start in a consistent state Time::Time() Constructor khi to cc thnh { vin d liu private v 0. hour = minute = second = 0; } // end Time constructor // set new Time value using universal time, perform validity // checks on the data values and set invalid values to zero void Time::setTime( int h, int m, int s ) { hour = ( h >= 0 && h < 24 ) ? h : 0; minute = ( m >= 0 && m < 60 ) ? m : 0; second = ( s >= 0 && s < 60 ) ? s : 0; } // end function setTime
2004 Trn Minh Chu. FOTECH. VNU.
Hm thnh vin public kim tra tnh hp l ca gi tr cc i s trc khi gn tr cho cc thnh vin d liu private
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
// print Time in universal format void Time::printUniversal() { cout << setfill( '0' ) << setw( 2 ) << hour << ":" << setw( 2 ) << minute << ":" << setw( 2 ) << second; } // end function printUniversal
24
fig06_03.cpp (3 of 5)
// print Time in standard format void Time::printStandard() { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":" << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); } // end function printStandard int main() { Time t;
Khng c tham s (ngm hiu mc ch l in cc thnh vin d liu); li gi hm thnh vin ngn gn hn li gi hm thng.
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
// output Time object t's initial values cout << "The initial universal time is "; t.printUniversal(); // 00:00:00
25
fig06_03.cpp (4 of 5) cout << "\nThe initial standard time is "; Gi cc hm thnh vin public in thi gian. t.printStandard(); // 12:00:00 AM
t.setTime( 13, 27, 6 ); // change time
// output Time object t's new values cout << "\n\nUniversal time after setTime is "; Th gn cc gi tr khng hp l cho cc thnh vin t.printUniversal(); // 13:27:06
// output t's values after specifying invalid values cout << "\n\nAfter attempting invalid settings:" << "\nUniversal time: "; t.printUniversal(); // 00:00:00
93 94 95 96 97 98 99
cout << "\nStandard time: "; t.printStandard(); // 12:00:00 AM cout << endl; return 0; } // end main
26
The initial universal time is 00:00:00 The initial standard time is 12:00:00 AM Universal time after setTime is 13:27:06 Standard time after setTime is 1:27:06 PM After attempting invalid settings: Universal time: 00:00:00 Standard time: 12:00:00 AM
6.5 Ci t mt kiu d liu tru tng Time bng mt lp - class li ch khi dng lp
n gin ha vic lp trnh cc giao din Interfaces
che du phn ci t Hide implementation
27
Chng 6.
28
bn ngoi phm vi lp
c gi n bng tn i tng, tham chiu/con tr ti i tng objectTime.printStandard()
Chng 6.
6.6 Phm vi lp v truy nhp cc thnh vin ca lp Phm vi file - File scope
p dng cho cc hm khng phi thnh vin
29
Chng 6.
6.6 Phm vi lp v truy nhp cc thnh vin ca lp Cc ton t truy nhp cc thnh vin ca i tng
ging cc ton t dnh cho struct ton t (.) dng cho
i tng tham chiu n i tng
30
Chng 6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// Fig. 6.4: fig06_04.cpp // Demonstrating the class member access operators . and -> // // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA! #include <iostream> using std::cout; using std::endl; // class Count definition class Count { public: int x; void print() { cout << x << endl; } }; // end class Count
31
fig06_04.cpp (1 of 2)
Thnh vin d liu public x minh ha cc ton t truy nhp; thng thng cc thnh vin d liu u l private.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
int main() { Count counter; Count *counterPtr = &counter; Count &counterRef = counter;
32
// create counter object S create chm cho i tng // dng du pointer to counter counter. // create reference to counter
fig06_04.cpp (2 of 2)
fig06_04.cpp cout << "Assign 1 to x and print using the object's name: "; output (1 of 1) counter.x = 1; // assign 1 to data member x S dng du chm cho counterRef l counter.print(); // call member function print tham chiu n i tng.
cout << "Assign 2 to x and print using a reference: "; counterRef.x = 2; // assign 2 dngdatatn cho counterPtr S to mi member x counterRef.print(); // call membertr ti i tng. l con function print cout << "Assign 3 to x and print using a pointer: "; counterPtr->x = 3; // assign 3 to data member x counterPtr->print(); // call member function print return 0; } // end main Assign 1 to x and print using the object's name: 1 Assign 2 to x and print using a reference: 2 Assign 3 to x and print using a pointer: 3
33
bt li
phi to cc file header gm mt phn ca ci t Inline member functions cc hm inline gi v phn khc ca ci t private members
Chng 6.
34
m rng ca file .h
Chng 6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
M tin x l trnh vic file b // Fig. 6.5: time1.h // Declaration of class Time. include nhiu ln. // Member functions are defined in time1.cpp If not defined
// prevent multiple inclusions of header file #ifndef TIME1_H #define TIME1_H
35
time1.h (1 of 1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// Fig. 6.6: time1.cpp // Member-function definitions for class Time. #include <iostream> using std::cout; #include <iomanip> using std::setfill; using std::setw;
36
time1.cpp (1 of 3)
// include definition of class Time from time1.h #include "time1.h" // Time constructor initializes each data member to zero. // Ensures all Time objects start in a consistent state. Time::Time() Tn ca header file t trong ngoc kp; { cp ngoc nhn lm trnh bin dch cho hour = minute = second = 0;
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
// Set new Time value using universal time. Perform validity // checks on the data values. Set invalid values to zero. void Time::setTime( int h, int m, int s ) { hour = ( h >= 0 && h < 24 ) ? h : 0; minute = ( m >= 0 && m < 60 ) ? m : 0; second = ( s >= 0 && s < 60 ) ? s : 0; } // end function setTime // print Time in universal format void Time::printUniversal() { cout << setfill( '0' ) << setw( 2 ) << hour << ":" << setw( 2 ) << minute << ":" << setw( 2 ) << second; } // end function printUniversal
37
time1.cpp (2 of 3)
42 43 44 45 46 47 48 49 50
// print Time in standard format void Time::printStandard() { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":" << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); } // end function printStandard
38
time1.cpp (3 of 3)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Fig. 6.7: fig06_07.cpp // Program to test class Time. // NOTE: This file must be compiled with time1.cpp. #include <iostream> using std::cout; using std::endl;
39
fig06_07.cpp (1 of 2)
// include definition of class Time from time1.h #include "time1.h" int main() { Time t;
// output Time object t's initial values cout << "The initial universal time is "; t.printUniversal(); // 00:00:00 cout << "\nThe initial standard time is "; t.printStandard(); // 12:00:00 AM t.setTime( 13, 27, 6 ); // change time
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
// output Time object t's new values cout << "\n\nUniversal time after setTime is "; t.printUniversal(); // 13:27:06 cout << "\nStandard time after setTime is "; t.printStandard(); // 1:27:06 PM t.setTime( 99, 99, 99 ); // attempt invalid settings
40
// output t's values after specifying invalid values cout << "\n\nAfter attempting invalid settings:" << "\nUniversal time: "; t.printUniversal(); // 00:00:00 cout << "\nStandard time: "; t.printStandard(); // 12:00:00 AM cout << endl; return 0; } // end main The initial universal time is 00:00:00 The initial standard time is 12:00:00 AM Universal time after setTime is 13:27:06 Standard time after setTime is 1:27:06 PM
41
6.8 Qun l quyn truy nhp thnh vin cc kiu truy nhp Access
private
kiu mc nh - Default access mode ch c cc hm thnh vin v cc hm friend l c th truy nhp cc thnh vin private
public
truy nhp c t mi hm trong chng trnh.
protected
dnh cho quan h tha k, hin ti cha ni n
Chng 6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Fig. 6.8: fig06_08.cpp // Demonstrate errors resulting from attempts // to access private class members. #include <iostream> using std::cout; // include definition of class Time from time1.h #include "time1.h" int main() { Time t;
42
fig06_08.cpp (1 of 1)
hour l thnh vin private; truy nhp cc thnh vin private s gy li.
t.hour = 7;
// error: 'Time::minute' is not accessible cout << "minute = " << t.minute; return 0; } // end main
43
6.8 Qun l quyn truy nhp thnh vin quyn truy nhp cc thnh vin ca class
mc nh private phi t tng minh public, protected
44
Chng 6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Fig. 6.9: salesp.h // SalesPerson class definition. // Member functions defined in salesp.cpp. #ifndef SALESP_H #define SALESP_H class SalesPerson { public: SalesPerson(); // void getSalesFromUser(); // void setSales( int, double ); // void printAnnualSales(); // private: double totalAnnualSales(); double sales[ 12 ]; }; // end class SalesPerson #endif
45
salesp.h (1 of 1) hm ghi d liu thc hin vic kim tra tnh hp l ca d liu (validity checks).
constructor input sales from keyboard set sales for a month summarize and print sales
hm tin ch private
// utility function // 12 monthly sales figures
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Fig. 6.10: salesp.cpp // Member functions for class SalesPerson. #include <iostream> using using using using std::cout; std::cin; std::endl; std::fixed;
46
salesp.cpp (1 of 3)
#include <iomanip> using std::setprecision; // include SalesPerson class definition from salesp.h #include "salesp.h" // initialize elements of array sales to 0.0 SalesPerson::SalesPerson() { for ( int i = 0; i < 12; i++ ) sales[ i ] = 0.0; } // end SalesPerson constructor
2004 Trn Minh Chu. FOTECH. VNU.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
// get 12 sales figures from the user at the keyboard void SalesPerson::getSalesFromUser() { double salesFigure; for ( int i = 1; i <= 12; i++ ) { cout << "Enter sales amount for month " << i << ": "; cin >> salesFigure; setSales( i, salesFigure ); } // end for } // end function getSalesFromUser
47
salesp.cpp (2 of 3)
hm ghi d liu thc hin vic kim tra tnh hp l ca d liu (validity checks).
// set one of the 12 monthly sales figures; function subtracts // one from month value for proper subscript in sales array void SalesPerson::setSales( int month, double amount ) { // test for valid month and amount values if ( month >= 1 && month <= 12 && amount > 0 ) sales[ month - 1 ] = amount; // adjust for subscripts 0-11 else // invalid month or amount value cout << "Invalid month or sales figure" << endl;
2004 Trn Minh Chu. FOTECH. VNU.
49 50 51 52 53 54 55 56 57 58 59
48 } // end function setSales // print total annual sales (with help of utility function) void SalesPerson::printAnnualSales() { cout << setprecision( 2 ) << fixed << "\nThe total annual sales are: $" << totalAnnualSales() << endl; // call utility function } // end function printAnnualSales
salesp.cpp (3 of 3)
Hm tin ch private phc v hm printAnnualSales; 60 61 // private utility function to total annual sales ng gi thao tc trn mng sales.
62 63 64 65 66 67 68 69 70 71 double SalesPerson::totalAnnualSales() { double total = 0.0; // initialize total for ( int i = 0; i < 12; i++ ) total += sales[ i ]; return total; } // end function totalAnnualSales
2004 Trn Minh Chu. FOTECH. VNU.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Fig. 6.11: fig06_11.cpp // Demonstrating a utility function. // Compile this program with salesp.cpp // include SalesPerson class definition from salesp.h #include "salesp.h" int main() { SalesPerson s; s.getSalesFromUser(); s.printAnnualSales(); return 0; } // end main
49
fig06_11.cpp (1 of 1)
// create SalesPerson object s // note simple sequential code; no // control structures in main
Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter
sales sales sales sales sales sales sales sales sales sales sales sales
amount amount amount amount amount amount amount amount amount amount amount amount
for for for for for for for for for for for for
month month month month month month month month month month month month
1: 5314.76 2: 4292.38 3: 4589.83 4: 5534.03 5: 4376.34 6: 5698.45 7: 4439.22 8: 5893.57 9: 4909.67 10: 5123.45 11: 4024.97 12: 5923.92
50
fig06_11.cpp output (1 of 1)
51
Cc gi tr khi to Initializers
c truyn di dng i s cho constructor khi khai bo bin: t trong cp ngoc n trc du chm phy
class Time { public: Time( int, int, int); ... }; // end class Time ... int main() { Time t( 27, 74, 99 ); ...
Chng 6.
52
c th ch nh cc i s mc nh
tng t i s mc nh ca hm thng thng
constructor mc nh:
c th gi khng cn tham s
Time t;
mi lp ch c c ti a mt constructor mc nh
Chng 6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Fig. 6.12: time2.h // Declaration of class Time. // Member functions defined in time2.cpp.
53
time2.h (1 of 1)
// prevent multiple inclusions of header file #ifndef TIME2_H #define TIME2_H // Time abstract data type definition class Time {
public: Time( int = 0, int = 0, int = 0); // default constructor void setTime( int, int, int ); // set hour, minute, second void printUniversal(); // print universal-time format void printStandard(); // print standard-time format private: int hour; int minute; int second;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// Fig. 6.13: time2.cpp // Member-function definitions for class Time. #include <iostream> using std::cout; #include <iomanip> using std::setfill; using std::setw; // include definition of class Time from time2.h #include "time2.h" // Time constructor initializes each data member to zero; // ensures all Time objects start in a consistent state Constructor gi setTime kim tra cc Time::Time( int hr, int min, int sec ) gi tr c truyn vo (hoc mc nh). { setTime( hr, min, sec ); // validate and set time } // end Time constructor
54
time2.cpp (1 of 2)
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
// set new Time value using universal time, perform validity // checks on the data values and set invalid values to zero void Time::setTime( int h, int m, int s ) { hour = ( h >= 0 && h < 24 ) ? h : 0; minute = ( m >= 0 && m < 60 ) ? m : 0; second = ( s >= 0 && s < 60 ) ? s : 0; } // end function setTime // print Time in universal format void Time::printUniversal() { cout << setfill( '0' ) << setw( 2 ) << hour << ":" << setw( 2 ) << minute << ":" << setw( 2 ) << second; } // end function printUniversal // print Time in standard format void Time::printStandard() { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":" << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); } // end function printStandard
55
time2.cpp (2 of 2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Fig. 6.14: fig06_14.cpp // Demonstrating a default constructor for class Time. #include <iostream> using std::cout; using std::endl; // include definition of class Time from time2.h #include "time2.h" int main() { Time t1; Time t2( Time t3( Time t4( Time t5(
56
fig06_14.cpp (1 of 2)
cout << "Constructed with:\n\n" << "all default arguments:\n "; t1.printUniversal(); // 00:00:00 cout << "\n "; t1.printStandard(); // 12:00:00 AM
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
cout << "\n\nhour specified; default minute and second:\n t2.printUniversal(); // 02:00:00 cout << "\n "; t2.printStandard(); // 2:00:00 AM cout << "\n\nhour and minute specified; default second:\n t3.printUniversal(); // 21:34:00 cout << "\n "; t3.printStandard(); // 9:34:00 PM cout << "\n\nhour, minute, and second specified:\n t4.printUniversal(); // 12:25:42 cout << "\n "; t4.printStandard(); // 12:25:42 PM cout << "\n\nall invalid values specified:\n t5.printUniversal(); // 00:00:00 cout << "\n "; t5.printStandard(); // 12:00:00 AM cout << endl; return 0; } // end main ";
";
57
fig06_14.cpp (2 of 2)
";
i s khng hp l, cc gi tr c gn v 0.
58
59
th t gi hm
ph thuc vo th t thc thi chng trnh
khi chng trnh vo v ra khi phm vi ca cc i tng
Chng 6.
60
Chng 6.
61
Chng 6.
62
Chng 6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Fig. 6.15: create.h // Definition of class CreateAndDestroy. // Member functions defined in create.cpp. #ifndef CREATE_H #define CREATE_H class CreateAndDestroy { public: CreateAndDestroy( int, char * ); ~CreateAndDestroy(); private: int objectID; char *message; }; // end class CreateAndDestroy #endif
63
// constructor // destructor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// Fig. 6.16: create.cpp // Member-function definitions for class CreateAndDestroy #include <iostream> using std::cout; using std::endl; // include CreateAndDestroy class definition from create.h #include "create.h" // constructor CreateAndDestroy::CreateAndDestroy( int objectNumber, char *messagePtr ) { objectID = objectNumber; message = messagePtr; cout << "Object " << objectID << " << message << endl; } // end CreateAndDestroy constructor
64
create.cpp (1 of 2)
23 24 25 26 27 28 29 30 31 32
65 Output message th hin thi gian // destructor ca cc li gi hm destructor CreateAndDestroy::~CreateAndDestroy() { create.cpp (2 of 2) // the following line is for pedagogic purposes only cout << ( objectID == 1 || objectID == 6 ? "\n" : "" ); cout << "Object " << objectID << " << message << endl; } // end ~CreateAndDestroy destructor destructor runs "
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
// Fig. 6.17: fig06_17.cpp // Demonstrating the order in which constructors and // destructors are called. #include <iostream> using std::cout; using std::endl; // include CreateAndDestroy class definition from create.h #include "create.h" void create( void ); // prototype
66
fig06_17.cpp (1 of 2)
// global object CreateAndDestroy first( 1, "(global before main)" ); int main() To i tng t ng a phng. { cout << "\nMAIN FUNCTION: EXECUTION BEGINS" << endl;
To cc i tng t ng a phng.
create(); // call function to create objects
2004 Trn Minh Chu. FOTECH. VNU.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
cout << "\nMAIN FUNCTION: EXECUTION RESUMES" << endl; CreateAndDestroy fourth( 4, "(local automatic in main)" ); cout << "\nMAIN FUNCTION: EXECUTION ENDS" << endl;
67
fig06_17.cpp (2 of 2)
To i tng t ng a phng.
return 0; } // end main // function to create objects void create( void ) To i tng t ng a phng bn trong hm. { cout << "\nCREATE FUNCTION: EXECUTION BEGINS" << endl;
Object 1
constructor runs
68
MAIN FUNCTION: EXECUTION BEGINS Object 2 constructor runs (local automatic in main) Object 3 constructor runs (local static in main) CREATE Object Object Object FUNCTION: EXECUTION BEGINS 5 constructor runs (local automatic in create) 6 constructor runs (local static in create) 7 constructor runs (local automatic in create)
fig06_17.cpp output (1 of 1)
CREATE FUNCTION: EXECUTION ENDS Object 7 destructor runs (local automatic in create) Object 5 destructor runs (local automatic in create) MAIN FUNCTION: EXECUTION RESUMES Object 4 constructor runs (local automatic in main) MAIN FUNCTION: EXECUTION ENDS Object 4 destructor runs Object 2 destructor runs Object 6 destructor runs Object 3 destructor runs Object 1 destructor runs
i tng staticcc i cc destructor cho a i tng ton cho c to phng tn ti a phng tng t ng cc n khi trc hm main ng a b cc i trnh t thc chng tngkt bta gi trong khi static u v i tng main c phng cng. hy th t ngc khi hm theocuib hy sauvi cc phng c th t ngc vi kt thc theo to ti li gi constructor. hmt to. v hy sau khi th u tin hm main kt thc.
69
Get functions cc hm c
cc hm truy vn Query functions qun l nh dng ca d liu tr v
Chng 6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Fig. 6.18: time3.h // Declaration of class Time. // Member functions defined in time3.cpp
70
time3.h (1 of 2)
// prevent multiple inclusions of header file #ifndef TIME3_H #define TIME3_H class Time { public: Time( int = 0, int = 0, int = 0 );
// default constructor
Cc hm ghi // set functions void setTime( int, int, int ); // set hour, minute, second void setHour( int ); // set hour void setMinute( int ); // set minute void setSecond( int ); // set second
// get functions int getHour(); int getMinute(); int getSecond();
cc hm c
// return hour // return minute // return second
2004 Trn Minh Chu. FOTECH. VNU.
25 26 27 28 29 30 31 32 33 34 35
void printUniversal(); // output universal-time format void printStandard(); // output standard-time format private: int hour; int minute; int second; }; // end clas Time #endif
71
time3.h (2 of 2)
// 0 - 23 (24-hour clock format) // 0 - 59 // 0 - 59
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Fig. 6.19: time3.cpp // Member-function definitions for Time class. #include <iostream> using std::cout; #include <iomanip> using std::setfill; using std::setw; // include definition of class Time from time3.h #include "time3.h" // constructor function to initialize private data; // calls member function setTime to set variables; // default values are 0 (see class definition) Time::Time( int hr, int min, int sec ) { setTime( hr, min, sec ); } // end Time constructor
72
time3.cpp (1 of 4)
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
// set hour, minute and second values void Time::setTime( int h, int m, int s ) { setHour( h ); setMinute( m ); setSecond( s ); } // end function setTime
73
time3.cpp (2 of 4)
// set hour value void Time::setHour( int h ) { hour = ( h >= 0 && h < 24 ) ? h : 0; } // end function setHour // set minute value void Time::setMinute( int m ) { minute = ( m >= 0 && m < 60 ) ? m : 0; } // end function setMinute
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
// set second value l trc khi sa i d liu. void Time::setSecond( int s ) { second = ( s >= 0 && s < 60 ) ? s : 0; } // end function setSecond // return hour value int Time::getHour() { return hour; } // end function getHour // return minute value int Time::getMinute() { return minute; } // end function getMinute
74
time3.cpp (3 of 4)
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
75
} // end function getSecond // print Time in universal format void Time::printUniversal() { cout << setfill( '0' ) << setw( 2 ) << hour << ":" << setw( 2 ) << minute << ":" << setw( 2 ) << second; } // end function printUniversal // print Time in standard format void Time::printStandard() { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":" << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); } // end function printStandard
2004 Trn Minh Chu. FOTECH. VNU.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Fig. 6.20: fig06_20.cpp // Demonstrating the Time class set and get functions #include <iostream> using std::cout; using std::endl; // include definition of class Time from time3.h #include "time3.h" void incrementMinutes( Time &, const int ); int main() { Time t; // prototype
76
fig06_20.cpp (1 of 3)
Gi cc hm set gn cc gi tr hp l.
// set time using individual set functions t.setHour( 17 ); // set hour to valid value t.setMinute( 34 ); // set minute to valid value t.setSecond( 25 ); // set second to valid value
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
// use get functions to obtain hour, minute and second cout << "Result of setting all valid values:\n" << " Hour: " << t.getHour() fig06_20.cpp << " Minute: " << t.getMinute() (2 << " Second: " << t.getSecond(); C dng cc hm set gnof 3)
77
cc gi tr khng hp l.
// set time using individual set functions t.setHour( 234 ); // invalid hour set to 0 t.setMinute( 43 ); // set minute to valid value t.setSecond( 6373 ); // invalid second set to 0
// display hour, minute and second after setting // invalid hour and second values cout << "\n\nResult of attempting to set invalid hour and" << " second:\n Hour: " << t.getHour() Sa i data member bng << " Minute: " << t.getMinute() << " Second: " << t.getSecond() << "\n\n"; hm setTime. t.setTime( 11, 58, 0 ); incrementMinutes( t, 3 ); return 0; } // end main // set time // increment t's minute by 3
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
// add specified number of minutes to a Time object void incrementMinutes( Time &tt, const int count ) { fig06_20.cpp cout << "Incrementing minute " << count (3 of 3) << " times:\nStart time: "; tt.printStandard(); Dng cc hm get c v
78
cc hm set sa d liu.
for ( int i = 0; i < count; i++ ) { tt.setMinute( ( tt.getMinute() + 1 ) % 60 ); if ( tt.getMinute() == 0 ) tt.setHour( ( tt.getHour() + 1 ) % 24); cout << "\nminute + 1: "; tt.printStandard(); Result of setting all valid values: Hour: 17 Minute: 34 Second: 25 } // end for cout << endl; Result of attempting to set invalid hour and second: Hour: 0 Minute: 43 Second: 0
} // end function incrementMinutes Incrementing minute 3 times: Start time: 11:58:00 AM minute + 1: 11:59:00 AM minute + 1: 12:00:00 PM minute + 1: 12:01:00 PM
C gng gn cc gi tr khng hp l cho cc thnh vin d liu, kt qu l thng Chu.li 2004 Trn Minh bo v cc thnh vin b gn v 0. FOTECH. VNU.
79
6.15 Php gn mc nh
Gn i tng cho i tng Php gn (=)
c th gn mt i tng cho mt i tng khc thuc cng kiu Mc nh: gn theo tng thnh vin (memberwise assignment) Mi thnh vin ca i tng v phi c gn cho thnh vin tng ng ti v tri
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// Fig. 6.24: fig06_24.cpp // Demonstrating that class objects can be assigned // to each other using default memberwise assignment. #include <iostream> using std::cout; using std::endl; // class Date definition class Date { public: Date( int = 1, int = 1, int = 1990 ); // default constructor void print(); private: int month; int day; int year; }; // end class Date
80
fig06_24.cpp (1 of 3)
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
// Date constructor with no range checking Date::Date( int m, int d, int y ) { month = m; day = d; year = y; } // end Date constructor // print Date in the format mm-dd-yyyy void Date::print() { cout << month << '-' << day << '-' << year; } // end function print int main() { Date date1( 7, 4, 2002 ); Date date2; // date2 defaults to 1/1/1990
81
fig06_24.cpp (2 of 3)
44 45 46 47 48 49 50 51 52 53 54 55 56 57
cout << "date1 = "; date1.print(); cout << "\ndate2 = "; date2.print(); date2 = date1;
php gn mc nh gn tng thnh vin ca date1 cho thnh vin tng ng ca date2.
82
cout << "\n\nAfter default memberwise assignment, date2 = "; date2.print(); cout << endl; return 0; } // end main
date1 = 7-4-2002 date2 = 1-1-1990 After default memberwise assignment, date2 = 7-4-2002