You are on page 1of 82

1

Ngn ng lp trnh C++


Chng 6 Cu trc d liu tru tng

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

Chng 6: Cu trc d liu tru tng


mc

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

2004 Trn Minh Chu. FOTECH. VNU

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)

2004 Trn Minh Chu. FOTECH. VNU

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

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

6.1 Gii thiu C++:


struct v class - kiu bn ghi i tng (mt th hin ca mt kiu struct hay class no ) - bn ghi thnh vin d liu - trng hm thnh vin/phng thc - thao tc trn cc thnh vin d liu

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

6.2 Cu trc - struct


struct definition
struct Time { int hour; int minute; int second; }; Structure tag Structure members

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;

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

6.2 Cu trc - struct


Self-referential structure - cu trc quy
thnh vin ca mt cu trc khng th thuc kiu cu trc thnh vin ca mt cu trc c th l con tr n kiu cu trc (self-referential structure - cu trc quy) s dng cho danh sch lin kt (linked list), hng i (queue), ngn xp (stack), v cy (tree) struct Node { int data; Node* next; };

2004 Trn Minh Chu. FOTECH. VNU

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;

timePtr->hour tng ng ( *timePtr ).hour


Cn c cp ngoc do * khng c u tin bng .

2004 Trn Minh Chu. FOTECH. VNU

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)

nh ngha kiu cu trc Time vi 3 thnh vin l s nguyn.

Truyn tham chiu ti hng Time trnh sao chp tham s.

2004 Trn Minh Chu. FOTECH. VNU.

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

int main() { Time dinnerTime; dinnerTime.hour = 18; dinnerTime.minute = 30; dinnerTime.second = 0;

10 // variable ofS dng k hiu du chm new type Time

khi to cc thnh vin cu trc. fig06_01.cpp (2 of 3) // set hour member of dinnerTime


// set minute member of dinnerTime // set second member of dinnerTime

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;

Quyn truy nhp trc tip ti d liu cho php gn cc gi tr khng hp l.

// set hour to invalid value // set minute to invalid value

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

fig06_01.cpp (3 of 3) fig06_01.cpp S dng manipulator (1 of 1) output setfill.

// 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

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

6.4 Ci t kiu d liu ngi dng Time bng struct


struct kiu C
khng c giao din gia bn trong v bn ngoi cu trc
Nu ci t thay i, mi chng trnh s dng struct phi c sa i theo

13

khng th in ra nh l mt bin n
Phi in/nh dng cho tng thnh vin

khng th so snh hai struct theo kiu thng thng


Phi so snh tng thnh vin

struct kiu C++


C++ m rng: struct c chc nng nh class thng l: struct ch c dng cho cc cu trc ch gm d liu; class dng cho cc lp c c d liu v hm thnh vin.

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

6.5 Ci t mt kiu d liu tru tng Time bng mt lp - class Cc lp - Classes


m hnh cc i tng
Thuc tnh - Attributes (data members) Hnh vi - Behaviors (member functions)

14

t kho class cc hm thnh vin member functions


cn c gi l cc phng thc - method c gi tr li cc thng ip

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

Class definition bt u bng t kho class.

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

Function prototype cho cc public member function.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 class 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 private: int hour; int minute; int second;

Nhn quyn truy nhp


// 0 - 23 (24-hour clock format) // 0 - 59 // 0 - 59

}; // end class Time

private data member ch c th c truy nhp t cc member function. Definition kt thc bng du chm phy.

Class body kt thc bng ngoc ng.

2004 Trn Minh Chu. FOTECH. VNU.

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

2004 Trn Minh Chu. FOTECH. VNU

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

c gi khi i tng c to, v d khi bin c khai bo c th c vi constructor


hot ng theo nguyn tc hm gi chng

khng c gi tr tr v v khng c kiu gi tr tr v


class Time { public: Time(); };
2004 Trn Minh Chu. FOTECH. VNU

Time::Time() { hour = minute = second = 0; } // end Time constructor

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

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

6.5 Ci t mt kiu d liu tru tng Time bng mt lp - class cc i tng ca mt lp


K t sau class definition
tn lp tr thnh tn kiu mi - type specifier C++ l ngn ng m rng c c th khai bo i tng, mng i tng, con tr v tham chiu ti i tng

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

2004 Trn Minh Chu. FOTECH. VNU

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

Cng thc nh ngha hm thnh vin


ReturnType ClassName::MemberFunctionName( ) { }

nh nhau i vi hm public hay private


2004 Trn Minh Chu. FOTECH. VNU 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 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

2004 Trn Minh Chu. FOTECH. VNU

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

2004 Trn Minh Chu. FOTECH. VNU.

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

private: int hour; int minute; int second;

23 // 0 - 23 (24-hour clock format) // 0 - 59 // 0 - 59

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.

Khai bo bin t l i tng thuc lp Time.


// instantiate object t of class Time

2004 Trn Minh Chu. FOTECH. VNU.

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

Dng hm thnh vin public gn tr cho cc thnh vin d liu.

d liu bng cch s dng hm thnh vin public


cout << "\nStandard time after setTime is "; t.printStandard(); // 1:27:06 PM t.setTime( 99, 99, 99 ); // attempt invalid settings

// output t's values after specifying invalid values cout << "\n\nAfter attempting invalid settings:" << "\nUniversal time: "; t.printUniversal(); // 00:00:00

2004 Trn Minh Chu. FOTECH. VNU.

93 94 95 96 97 98 99

cout << "\nStandard time: "; t.printStandard(); // 12:00:00 AM cout << endl; return 0; } // end main

26

fig06_03.cpp (5 of 5) fig06_03.cpp output (1 of 1)

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

Cc thnh vin d liu c gn v 0 sau khi th cc gi tr khng hp l.

2004 Trn Minh Chu. FOTECH. VNU.

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

ti s dng phn mm Software reuse


kh nng tch hp Composition (aggregation) cc thnh vin ca mt lp c th l i tng thuc lp khc tha k - Inheritance cc lp mi c to t lp c

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

6.6 Phm vi lp v truy nhp cc thnh vin ca lp phm vi lp Class scope


gm thnh vin d liu v hm thnh vin ca lp bn trong phm vi lp
Cc thnh vin ca lp c th c truy nhp thng t mi hm thnh vin gi bng tn

28

bn ngoi phm vi lp
c gi n bng tn i tng, tham chiu/con tr ti i tng objectTime.printStandard()

2004 Trn Minh Chu. FOTECH. VNU

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

Phm vi hm Function scope


Gm cc bin c khai bo trong hm thnh vin ch c bit n trong hm b hy khi hm kt thc cc bin trng tn vi bin thuc phm vi lp
bin thuc phm vi lp (class-scope variable) b che (hidden) truy nhp bng ton t phm vi (::) ClassName::classVariableName

2004 Trn Minh Chu. FOTECH. VNU

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

ton t (->) dng cho


cc con tr ti i tng

2004 Trn Minh Chu. FOTECH. VNU

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.

2004 Trn Minh Chu. FOTECH. VNU.

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

2004 Trn Minh Chu. FOTECH. VNU.

33

6.7 Tch giao din ra khi ci t

Tch giao din khi ci t


ch li
d sa i chng trnh

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

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

34

6.7 Tch giao din ra khi ci t Cc file header


cha cc nh ngha lp v cc nguyn mu hm c include trong mi file s dng lp
#include

m rng ca file .h

Cc file m ngun Source-code files


cha nh ngha ca cc hm thnh vin trng tn file vi file header tng ng (khng k phn m rng)
y ch l thng l, khng bt buc

c bin dch v lin kt vi file chng trnh chnh

2004 Trn Minh Chu. FOTECH. VNU

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)

M gia hai nh hng ny khng c


// Time abstract data type definition include nn tn TIME1_H c nh ngha. class 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 private: int hour; int minute; int second;

nh hng tin x l nh ngha tn TIME1_H.

// 0 - 23 (24-hour clock format) // 0 - 59 // 0 - 59

}; // end class Time #endif

Thng l t tn: tn header file vi du gch di thay cho du chm.


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 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 header file time1.h.

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

rng l mt phn ca th vin chun C++ (C++ Standard Library).

} // end Time constructor

2004 Trn Minh Chu. FOTECH. VNU.

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)

2004 Trn Minh Chu. FOTECH. VNU.

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)

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 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 time1.h m bo to ng v tnh kch thc i tng thuc lp Time.

// include definition of class Time from time1.h #include "time1.h" int main() { Time t;

// instantiate object t of class Time

// 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

2004 Trn Minh Chu. FOTECH. VNU.

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

fig06_07.cpp (2 of 2) fig06_07.cpp output (1 of 1)

// 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

2004 Trn Minh Chu. FOTECH. VNU.

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

2004 Trn Minh Chu. FOTECH. VNU

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)

// create Time object

hour l thnh vin private; truy nhp cc thnh vin private s gy li.

t.hour = 7;

// error: 'Time::hour' is not accessible

// error: 'Time::minute' is not accessible cout << "minute = " << t.minute; return 0; } // end main

minute cng l private;

2004 Trn Minh Chu. FOTECH. VNU.

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

quyn truy nhp cc thnh vin ca struct


mc nh public phi t tng minh private, protected

truy nhp d liu private ca lp


cc hm truy nhp (accessor method)
Get function hm c d liu c d liu private Set function hm ghi d liu ghi d liu private
2004 Trn Minh Chu. FOTECH. VNU Chng 6.

44

6.9 Cc hm truy nhp v cc hm tin ch Cc hm truy nhp Access functions


public cc hm c v hin th d liu cc hm ghi d liu (km kim tra tnh hp l) cc hm mnh Predicate functions
kim tra cc iu kin

Cc hm tin ch Utility functions


private ch h tr hot ng ca cc hm thnh vin kiu public khng nhm mc ch cho client trc tip s dng

2004 Trn Minh Chu. FOTECH. VNU

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

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

// summarize sales results

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)

Chui gi hm n gin; logic chng trnh c ng gi trong cc hm thnh vin.

// create SalesPerson object s // note simple sequential code; no // control structures in main

2004 Trn Minh Chu. FOTECH. VNU.

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)

The total annual sales are: $60120.59

2004 Trn Minh Chu. FOTECH. VNU.

51

6.10 Khi to cc i tng: Constructor Constructors


khi to cc thnh vin d liu
hoc c th gn tr cho cc thnh vin d liu sau

trng tn vi tn lp khng c kiu tr v

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

Class-type ObjectName( value1,value2,);

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

6.11 S dng cc i s mc nh vi constructor

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;

Tt c cc i s l mc nh HOC thc s khng nhn tham s


Time(int = 0, int = 0, int = 0); hoc Time();

mi lp ch c c ti a mt constructor mc nh

2004 Trn Minh Chu. FOTECH. VNU

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 {

Default constructor ch nh gi tr mc nh cho mi i s.

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;

// 0 - 23 (24-hour clock format) // 0 - 59 // 0 - 59

}; // end class Time #endif


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

2004 Trn Minh Chu. FOTECH. VNU.

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)

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

Khi to cc i tng Time s dng cc tham s mc nh.


// 2 ); // 21, 34 ); // 12, 25, 42 ); // 27, 74, 99 ); // all arguments defaulted minute and second defaulted second defaulted all values specified all bad values specified

cout << "Constructed with:\n\n" << "all default arguments:\n "; t1.printUniversal(); // 00:00:00 cout << "\n "; t1.printStandard(); // 12:00:00 AM

Khi to i tng Time vi cc gi tr khng hp l; khu kim tra tnh hp l s gn cc gi tr v 0.

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

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

"; t5 c xy dng bng cc

i s khng hp l, cc gi tr c gn v 0.

2004 Trn Minh Chu. FOTECH. VNU.

58

6.12 Destructor hm hy Destructor hm thnh vin t hy ca i tng


hm thnh vin c bit trng tn vi tn lp
bt u bng du ng (~)

khng nhn i s khng c gi tr tr v khng th b gi chng thc hin vic dn dp


trc khi h thng ly li phn b nh ca i tng ti s dng cho i tng mi

nu khng c destructor c nh ngha tng minh


trnh bin dch t to destructor "rng" khng lm g ht
2004 Trn Minh Chu. FOTECH. VNU Chng 6.

6.13 Khi no Constructor v Destructor c gi cc constructor v destructor


c gi ngm bi trnh bin dch

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

cc i tng cng l cc bin thng thng,


bin c khi to constructor c gi ti thi im bt u tn ti / phm vi bin b hy destructor c gi khi kt thc s tn ti / ra khi phm vi

thng thng, cc li gi destructor theo th t ngc li vi th t gi cc constructor

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

6.13 Khi no Constructor v Destructor c gi Th t cc li gi constructor, destructor


i vi cc i tng/bin phm vi ton cc (global scope objects)
Constructor c gi trc mi hm khc (k c main) Destructor c gi khi main kt thc (hoc khi hm exit c gi) khng c gi nu chng trnh kt thc bng hm abort

60

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

6.13 Khi no Constructor v Destructor c gi Th t cc li gi constructor, destructor


i vi cc i tng/bin a phng (automatic local objects)
Constructor c gi khi i tng c nh ngha mi khi chng trnh vo phm vi ca i tng Destructor c gi khi i tng ra khi phm vi chng trnh ra khi khi ni i tng c nh ngha khng c gi nu chng trnh kt thc bng exit hay abort

61

2004 Trn Minh Chu. FOTECH. VNU

Chng 6.

6.13 Khi no Constructor v Destructor c gi Th t cc li gi constructor, destructor


cc i tng tnh a phng (static local objects)
Constructor ng mt ln khi chng trnh chy n ch i tng c nh ngha Destructor khi hm main kt thc hoc khi hm exit c gi khng c gi nu chng trnh kt thc bng hm abort

62

2004 Trn Minh Chu. FOTECH. VNU

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

create.h (1 of 1) Cc hm thnh vin constructor v destructor

// constructor // destructor

Cc thnh vin private minh ha th t cc li gi constructor v destructor

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

Output message th hin thi gian ca cc li gi hm constructor.


constructor runs "

2004 Trn Minh Chu. FOTECH. VNU.

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 "

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

to i tng c phm vi ton cc

// global object CreateAndDestroy first( 1, "(global before main)" ); int main() To i tng t ng a phng. { cout << "\nMAIN FUNCTION: EXECUTION BEGINS" << endl;

To i tng a phng static.


CreateAndDestroy second( 2, "(local automatic in main)" ); static CreateAndDestroy third( 3, "(local static in main)" );

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;

To i tng a phng static bn trong hm.


CreateAndDestroy fifth( 5, "(local automatic in create)" ); static CreateAndDestroy sixth( 6, "(local static in create)" ); CreateAndDestroy seventh( 7, "(local automatic in create)" ); cout << "\nCREATE FUNCTION: EXECUTION ENDS\" << endl; } // end function create
2004 Trn Minh Chu. FOTECH. VNU.

To i tng t ng a phng bn trong hm.

Object 1

constructor runs

(global before main)

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.

(local (local (local (local

automatic automatic static in static in

in main) in main) create) main)

(global before main)

2004 Trn Minh Chu. FOTECH. VNU.

69

6.14 S dng cc hm truy nhp Set functions cc hm ghi


kim tra tnh hp l trc khi sa i d liu private thng bo nu cc gi tr l khng hp l thng bo qua cc gi tr tr v

Get functions cc hm c
cc hm truy vn Query functions qun l nh dng ca d liu tr v

2004 Trn Minh Chu. FOTECH. VNU

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

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

2004 Trn Minh Chu. FOTECH. VNU.

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)

Gi cc hm set d kim tra tnh hp l.

// 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

Cc hm set kim tra tnh hp l trc khi sa i d liu.

2004 Trn Minh Chu. FOTECH. VNU.

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

Cc hm set kim tra tnh hp

74

time3.cpp (3 of 4)

Cc hm get cho client c d liu

2004 Trn Minh Chu. FOTECH. VNU.

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

// return second value int Time::getSecond() { return second;

75

time3.cpp (4 of 4) Hm get cho client c d liu

} // 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)

// create Time object

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

2004 Trn Minh Chu. FOTECH. VNU.

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

cc gi tr khng hp l lm cc data member b gn v 0.

2004 Trn Minh Chu. FOTECH. VNU.

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

c ngm thc hin khi


truyn tham s l i tng tr v i tng

i tng c th c truyn lm tham s cho hm


i tng c th c hm tr v Mc nh: pass-by-value
Bn sao ca i tng c truyn, tr v s dng 'copy constructor' sao chp cc gi tr gc vo i tng mi
2004 Trn Minh Chu. FOTECH. VNU 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.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)

2004 Trn Minh Chu. FOTECH. VNU.

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)

2004 Trn Minh Chu. FOTECH. VNU.

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

fig06_24.cpp (3 of 3) fig06_24.cpp output (1 of 1)

// default memberwise assignment

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

2004 Trn Minh Chu. FOTECH. VNU.

You might also like