You are on page 1of 109

Lp trnh hng i tng C++

Tng quan

Lp trnh cu trc
Lp trnh cu trc (1960s)
Phn chia vn ln thnh cc vn con c lp, t to thnh th tc v hm. Trng tm ca lp trnh truyn thng: da trn cc chi tit ca vic thc hin. Phng php vit chng trnh cht ch R rng, d th nghim v sa li, d thay i Khi chng trnh ln hn kh qun l D liu ng vai tr quan trng
Khi thm 1 d liu kiu mi, phi thay i tt c cc cng vic v cc hm lin quan n d liu Khng th phn chia cc phn cn che du thng tin trong chng trnh.

Lp trnh hng i tng


Object oriented programming (OOP)
Chia bi ton thnh cc nhm nh c lin h vi nhau gi l i tng.

i Tng (Object)
i tng l cha kha hiu c k thut hng i tng Trong h thng hng i tng, mi th u l i tng
Vit mt chng trnh hng i tng ngha l ang to mt m hnh ca mt vi b phn trong th gii thc

i tng (Object)
What is the salary of Jack?
Sales

Jack's salary is $2000


Accounts

Hp en cha cc lnh (code) v d liu. Thng tin truyn gia cc phn khc nhau gi l cc thng ip gia cc i tng. Cc thng ip ny c th c chuyn thnh li gi hm trong chng trnh.

i Tng

i tng phn mm

i tng phn mm Xe p

i tng (object) l mt thc th phn mm bao bc cc thuc tnh v cc phng thc lin quan.

Thuc tnh c xc nh bi gi tr c th gi l thuc tnh th hin. Mt i tng c th c gi l mt th hin.

i Tng Th Gii Thc (Real Object)


Mt i tng th gii thc l mt thc th c th m thng thng bn c th s, nhn thy hay cm nhn c.
Tt c c trng thi (state) v hnh ng (behaviour)

i Tng Phn Mm (Software Object)


Cc i tng phn mm c th c dng biu din cc i tng th gii thc.

Cng c trng thi v hnh ng


Trng thi: thuc tnh (attribute; property) Hnh ng: phng thc (method)

Lp (Class)
Nhm cc i tng c cng thuc tnh, hnh vi v mi quan h chung. Lp l vit tt ca lp ca i tng. Mt lp l mt thit k (blueprint) hay mu (prototype) cho cc i tng cng kiu
V d: lp XeDap l mt thit k chung cho nhiu i tng xe p c to ra

Mt i tng l mt th hin c th ca mt lp.


V d: mi i tng xe p l mt th hin ca lp XeDap

Mi th hin c th c nhng thuc tnh th hin khc nhau


V d: mt cy mai c hoa 6 cnh, trong khi mt cy khc c hoa n 12 cnh.

Thuc Tnh Lp & Phng Thc Lp


i tng a gic Lp a gic Thuc tnh (properties): S cnh Mu vin Mu nn Phng thc (methode): V Xa Di chuyn

Tru tng ha

Thuc Tnh Lp & Phng Thc Lp


Thuc tnh lp (class attribute): c trng yu cu ca i tng hoc thc th c biu din trong mt lp. Thuc tnh lp c nh ngha bn trong nh ngha lp v c chia s bi tt c cc th hin ca lp.
V d: Lp a gic gm cc thuc tnh nh: s cnh, mu vin, mu ch

Phng thc lp (class method): phng thc (hnh ng) yu cu ca i tng hoc thc th c biu din trong mt lp. Tt c cc phng thc lp nh hng n ton b lp ch khng nh hng n mt lp ring r no.
V d: Lp a gic gm cc phng thc nh: v, xa, di chuyn

Thng ip & Truyn Thng ip


Thng ip (message) l mt li yu cu mt hot ng. Gm c:
i tng nhn thng ip Tn ca phng thc thc hin Cc tham s m phng thc cn

Truyn thng ip: mt i tng triu gi mt hay nhiu phng thc ca i tng khc yu cu thng tin.

c im Quan Trng
Nhn mnh trn d liu hn l th tc Cc chng trnh c chia thnh cc i tng D liu c che giu v khng th c truy xut t cc hm bn ngoi Cc i tng c th giao tip vi nhau thng qua cc hm D liu hay cc hm mi c th c thm vo khi cn Theo tip cn t di ln

Thun Li
So vi cc tip cn c in th OOP c nhng thun li sau:
OOP cung cp mt cu trc module r rng
Giao din c nh ngha tt Nhng chi tit ci t c n OOP gip lp trnh vin duy tr m v sa i m tn ti d dng (cc i tng c to ra vi nhng khc nhau nh so vi nhng i tng tn ti). OOP cung cp mt c ch tt vi cc th vin m m cc thnh phn c th c chn v sa i bi lp trnh vin.

Tru Tng Ha (Abstraction)


Tru tng ha
Tin trnh xem xt cc kha cnh no ca bi ton. Biu din nhng c tnh, b qua nhng chi tit vn vt hoc nhng gii thch.

Cc k thut tru tng


ng gi (encapsulation) n thng tin (information hiding) Tha k (inheritance) a hnh (polymorphism)

Tnh ng gi (Encapsulation)
ng gi (encapsulation):
Cho php truy cp i tng ch qua thng ip ca n trong khi gi kn cc chi tit ring t gi l n thng tin. L tin trnh che giu vic thc thi chi tit ca mt i tng.

n thng tin (Information Hiding)


ng gi Thuc tnh c lu tr hay phng thc c ci t nh th no c che giu i t cc i tng khc
Vic che giu nhng chi tit thit k v ci t t nhng i tng khc c gi l n thng tin

Tnh Tha K (Inheritance)


H thng hng i tng cho php cc lp c nh ngha k tha t cc lp khc
V d, lp xe p leo ni v xe p ua l nhng lp con (subclass) ca lp xe p.

Tha k ngha l cc phng thc v cc thuc tnh c nh ngha trong mt lp c th c tha k hoc c s dng li bi lp khc.

Tnh a Hnh (Polymorphism)


a hnh: nhiu hnh thc, hnh ng cng tn c th c thc hin khc nhau i vi cc i tng/cc lp khc nhau. Ng cnh khc kt qu khc
im ng Thng Hnh Trn Hnh Vung

Lp

Khi nim lp
Lp: khi nim trung tm ca OOP nh ngha: Lp l nhm ca nhng i tng (objects) c cng chung thuc tnh (properties) v c nhng mi quan h chung i tng: th hin mt thc th trong th gii thc.

Khi nim lp
Lp: kiu d liu tru tng.
c t i tng

private protected public

TN LP

D liu thnh vin

Tp cc thao tc

Hm thnh vin

class TNLP [: <Quyn truy xut> LPCHA ] { <Quyn truy xut > : DataType1 memberdata1; DataType2 memberdata2; . < Quyn truy xut > : memberFunction1(); memberFunction2(); .. };

Lp n gin
V d:
class Point { int xVal, yVal; public: void SetPt (int, int); void OffsetPt (int, int); }; void Point::SetPt (int x, int y) { xVal = x; yVal = y; } void Point::OffsetPt (int x, int y) { xVal += x; yVal += y; } void main() { Point pt; pt.SetPt(10,20); pt.OffsetPt(2,2); ..

To ra i tng thuc lp Point

Khai bo Lp

Gi hm trn i tng

nh ngha cc hm thnh vin

pt.xVal = 10; // ng hay sai? Point pt1, pt2, pt3; . }

C bn v lp
Lp gm cc thnh vin:
D liu thnh vin (Member Data):
Mt c trng ca i tng C th l kiu c nh ngha hoc t nh ngha D liu thnh vin ca lp khng th c kiu ca lp , nhng c th l con tr kiu lp .

Hm thnh vin (Member Function) hay phng thc (Method)


Mt hot ng, hnh vi ca i tng i tng l hp en nhn v gi thng ip (message)

C bn v lp
i tng ca lp
Khai bo sau nh ngha lp Khai bo i tng hoc mng, con tr, tham chiu n i tng V d:
Point pt;

Point polygon[9]; Point *pt1, pt2, pt3;

Ch d liu ca i tng mi c cp pht vng nh, cc hm thnh vin khng c vng nh ring.

C bn v lp
Cc hm thnh vin nh ngha ngoi lp
S dng ton t :: Lin kt tn hm thnh vin vi tn lp Cc lp khc nhau c th c cc hm trng tn nh dng nh ngha cc hm thnh vin Kiutrv Tnlp::Tnhmthnhvin( ) { } Khng ph thuc vo hm public hay private

Cc hm thnh vin nh ngha bn trong lp


Khng cn ton t :: v tn lp Trnh bin dch s c thc hin inline ngoi lp, ta ch nh inline vi t kho inline

Hm thnh vin ni tuyn


Hm inline:
Ci thin tc thc thi Tn b nh (dnh cho m lnh) khi thc thi.
Cch 1:

thm T kha inline

class Point { int xVal, yVal; public: void SetPt (int, int); void OffsetPt (int, int); };

inline void Point::SetPt (int x, int y) { xVal = x; yVal = y; }

class Point { int xVal, yVal; Cch 2: public: void SetPt (int x, int y) { nh xVal = x; ngha yVal = y; bn } trong void OffsetPt (int x, int y) { xVal += x; lp yVal += y; }

};

Truy cp cc thnh phn (d liu v hm)


Cc ch truy cp
private Ch truy cp mc nh Cc hm thnh phn v cc hm bn, lp bn c th truy cp c public Bt k hm no trong chng trnh x l i tng cng c th truy cp c protected S c hc sau. Hin ti ging vi private

D liu mc nh l private m bo giu kn Hm mc nh l public c th dng mi ni

Cc hm truy cp v cc hm hu dng
Cc hm truy cp
public
c/xut d liu Cc hm xc nh tnh cht Kim tra cc iu kin

Cc hm hu dng (cc hm gip )


private H tr hot ng ca cc hm thnh phn public Khng dnh cho ngi dng trc tip

S ng gi (encapsulation)
S truy xut n i tng thng qua cc thng ip (message) m vn gi cc thuc tnh private di dng thng tin n Lm cho vic truy xut n d liu ca cc lp t bn ngoi lp b gii hn, tr nn khng cn thit hoc khng th thc hin c Ngi dng khng cn quan tm n cu trc v hot ng bn trong ca lp, ch quan tm gii quyt vn ln hn Mc tiu:
to bc tng khng th thm nhp c bo v, trnh nhng h hi v tnh hoc c do nhng li chng ta mc phi D dng c lp li d dng tm kim v sa cha

Hm to
Dng nh ngha v khi to i tng cng 1 lc. C tn trng vi tn lp, khng c kiu tr v. Khng gi trc tip, s c t ng gi khi khi to t. Gn gi tr, cp vng nh cho cc d liu thnh vin.
class Point { int xVal, yVal; public: Point (int x, int y) { xVal = x; yVal = y; } void OffsetPt (int x, int y) { xVal += x; yVal += y; } void main() { Point pt1(10,20); pt1.OffsetPt(2,2); .. // Khai bo no l sai ? Point pt2; Point pt3(); Point pt4 = Point(5,5); Point pt5 = new Point(5,5); . }

};

V cch khai bo ny ng vi hm to khng tham s

Hm to
class Point { int xVal, yVal; public: Point () // Hm to mc nh { xVal = 0; yVal = 0; } Point (int x, int y) { xVal = x; yVal = y; } Point (float len, float angle) {
xVal = (int) (len * cos(angle)); yVal = (int) (len * sin(angle));

} void OffsetPt (int , int );

};
void main() {
Point p1; Point p2(10,20); Point p3(60.3, 3.14);

class Set { private: int *elems; int maxCard; int card; public: Set(const int size) { elems = new int[size]; maxCard = size; card = 0; } }; void main() { Set s1(100); Set s2(20); Set s3(1000); }

Mm do hn

Khng cn phi nh gi hm EmptySet() khi khi to

Hm hy
Gii phng 1 i tng trc khi n c thu hi. C php: ~TenLop() { ... } Khng gi trc tip, s c t ng gi khi hy b i tng. Thu hi vng nh cho cc d liu thnh vin l con tr.
class Set { private: int *elems; int maxCard; int card; public: Set(const int size) { } ~Set() { delete[] elems; } . };
Set TestFunct1(Set s1) { Set *s = new Set(50); return *s; } void main() { Set s1(40), s2(50); s2 = TestFunct1(s1); }

Tng cng c bao nhiu ln hm hy c gi ? 4

Hm to v hm hy mc nh
Hm to mc nh:
Thng to hm to v hm hy khi lp c thnh phn cp pht ng Nu lp khng c hm to th trnh bin dch s cung cp 1 hm to mc nh khng i. Hm ny ch cp pht b nh, khng khi to d liu. Nu lp c hm to th s khng c hm to mc nh mi c pht sinh.

Hm hy mc nh tng t nh trn.

i s mc nh
class Point { int xVal, yVal; public: Point (int x = 0, int y = 0); //... }; void main() { Point p1; // nh l ??? Point p2(10); // nh l ??? Point p3(10,20); Point p4(, 20); // ????? .. } class Point { int xVal, yVal; public: Point (int x = 0, int y = 0); Point (float x=0, float y=0); //... }; Ti ngha M h void main() { Point p2(1.6, 5.0); // nh l ??? Point p3(10,20); // nh l ??? Point p4; // ????? .. }

i s thnh vin n
Con tr *this:
L 1 thnh vin n, c thuc tnh l private. Tr ti chnh bn thn i tng.
void Point::OffsetPt (int x, int y) { xVal += x; yVal += y; } void Point::OffsetPt (int x, int y) { this->xVal += x; this->yVal += y; }

C nhng trng hp s dng *this l d tha (V d trn)

Tuy nhin, c nhng trng hp phi s dng con tr *this

S dng con tr this


Cc li gi hm thnh phn lin tip
Nhiu hm c gi trong cng 1 lnh Hm tr v 1 tham chiu n cng i tng
{ return *this; }

Cc hm khc hot ng trn con tr ny Hm khng tr v tham chiu phi c gi sau cng

S dng con tr this


1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. #include <iostream.h> class Time { int hour, minute, second ; public: Time( int = 0, int = 0, int = 0 ); // default constructor Time &setTime(int,int,int); // set hour,minute,second Time &setHour( int ); // set hour Time &setMinute( int ); // set minute Time &setSecond( int ); // set second int getHour() const; // return hour int getMinute() const; // return minute int getSecond() const; // return second void printUniversal() const; // print universal time void printStandard() const; // print standard time }; // end class Time

16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30.

Time::Time( int hr, int min, int sec ) { setTime( hr, min, sec ); } // end Time constructor Time &Time::setTime( int h, int m, int s ) { setHour( h ); setMinute( m ); setSecond( s ); return *this; // enables cascading } // end function setTime Time &Time::setHour( int h ) { hour = ( h >= 0 && h < 24 ) ? h : 0; return *this; // enables cascading } // end function setHour Time &Time::setMinute( int m ) { minute = ( m >= 0 && m < 60 ) ? m : 0; return *this; // enables cascading } // end function setMinute

31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46.

Time &Time::setSecond( int s ) { second = ( s >= 0 && s < 60 ) ? s : 0; return *this; // enables cascading } // end function setSecond int Time::getHour() const { return hour; } // end function getHour int Time::getMinute() const { return minute; } // end function getMinute int Time::getSecond() const { return second; } // end function getSecond void Time::printUniversal() const { cout << hour << ": << minute << ": << second; } // end function printUniversal

47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62.

void Time::printStandard() const { cout << ((hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":" << minute << ":" << second << ( hour < 12 ? " AM" : " PM" ); } // end function printStandard void main() { Time t; t.setHour( 18 ).setMinute( 30 ).setSecond( 22 ); cout << "Universal time: "; t.printUniversal(); cout << "\nStandard time: "; t.printStandard(); cout << "\n\nNew standard time: "; t.setTime( 20, 20, 20 ).printStandard(); cout << endl; } // end main

Bn (Friend) t vn
Tp Cc S Nguyn class IntSet { public: //... private: int elems[maxCard]; int card; }; class RealSet { public: //... Tp Cc private: S Thc float elems[maxCard]; int card; }; Hm SetToReal dng chuyn tp s nguyn thnh tp s thc void IntSet::SetToReal (RealSet &set) { set.card = card; for (register i = 0; i < card; ++i) set.elems[i] = (float) elems[i]; }

Lm th no thc hin c vic truy xut n thnh vin Private ?

Hm bn (Friend)
Cch 1: Khai bo hm thnh vin ca lp
IntSet l bn (friend) ca lp RealSet.
Gi nguyn nh ngha ca lp IntSet class IntSet { public: //... private: int elems[maxCard]; int card; }; class RealSet { public: //... friend void IntSet::SetToReal (RealSet &); private: float elems[maxCard]; int card; };

Thm dng khai bo Friend cho hm thnh vin SetToReal

Hm bn (Friend)
Cch 2:
Chuyn hm SetToReal ra ngoi (c lp). Khai bo hm l bn ca c 2 lp.
class IntSet { public: //... friend void SetToReal (IntSet &, RealSet&); private: int elems[maxCard]; int card; }; class RealSet { public: //... friend void SetToReal (IntSet &, RealSet&); private: float elems[maxCard]; int card; }; void SetToReal (IntSet& iSet, RealSet& rSet ) { rSet.card = iSet.card; for (int i = 0; i < iSet.card; ++i) rSet.elems[i] = (float) iSet.elems[i]; } Hm c lp l bn(friend) ca c 2 lp.

Bn (Friend)
Hm bn:
C quyn truy xut n tt c cc d liu v hm thnh vin (protected + private) ca 1 lp. L do:
Cch nh ngha hm chnh xc. Hm ci t khng hiu qu.

Lp bn:
Tt c cc hm trong lp bn: l hm bn.
class A; class B { // . friend class A; }; class IntSet { .. } class RealSet { // . friend class IntSet; };

Cc hm thnh vin ca lp A u l bn ca lp B

Hm bn v lp bn
Tnh cht ca tnh bn
Tnh bn c cp, khng t dng c c
Lp B l friend ca lp A Lp A phi khai bo r rng lp B l friend

Khng i xng
Lp B l friend ca lp A Lp A khng nht thit l friend ca lp B

Khng bt cu
Lp A l friend ca lp B Lp B l friend ca lp C Lp A khng nht thit l friend ca lp C

Hm thnh vin v hm c lp
class SP { double r; double i; public: SP cong(SP s2) { SP temp; temp.r = r+ s2.r ; temp.i = i+ s2.i ; return temp; } }; Cch dng: SP s, s1, s2; s=s1.cong(s2); class SP { double r; double i; public: friend SP cong(SP s1,SP s2) { SP temp; temp.r = s1.r+ s2.r ; temp.i = s1.i+ s2.i ; return temp; } }; Cch dng: SP s, s1, s2; s=cong(s1,s2);

1. // Use a friend function. 2. #include <iostream> 3. const int IDLE=0; 4. const int INUSE=1; 5. class C2; // note : forward declaration 6. class C1 7. { int status; // IDLE if off, INUSE if on screen 8. // ... 9. public: 10. void set_status(int state); 11. friend int idle(C1 a, C2 b); 12. }; 13.class C2 14. { int status; // IDLE if off, INUSE if on screen 15. // ... 16. public: 17. void set_status(int state); 18. friend int idle(C1 a, C2 b); 19. };

20.void C1::set_status(int state) { status = state; } 21.void C2::set_status(int state) { status = state; } 22.// idle( ) is a friend of C1 and C2. 23.int idle(C1 a, C2 b) 24. { if(a.status || b.status) return 0; else return 1; } 25.void main() 26. { C1 x; 27. C2 y; 28. x.set_status(IDLE); 29. y.set_status(IDLE); 30. 31. 32. 33. 34. 35. if(idle(x, y)) cout << "Screen Can Be Used.\n"; else cout << "Pop-up In Use.\n"; x.set_status(INUSE); if(idle(x, y)) cout << "Screen Can Be Used.\n"; else cout << "Pop-up In Use.\n"; }

Hm bn v lp bn
Ch : Hm bn khng c con tr this Li ch ca hm bn v lp bn:
Qu ti ton t
S c hc sau

n gin mt vi hm I/O
S c hc sau

Cc thnh phn ca 2 lp (hoc nhiu hn) c lin quan n phn khc ca chng trnh
V d: Hm print cn xut thng tin ca 2 i tng thuc 2 lp khc nhau

Hm bn v lp bn
Thun li:
Cung cp mt s t do trong vic thit k giao din

Kh khn:
i ngc li nguyn l OOP
Ph v encapsulation C th hn ch s vi phm tnh ton vn trong mt chng mc no

Khi 1 hm l hm bn ca 1 lp, n c th truy cp d liu ca lp . Ngi lp trnh cn bit m ngun hn ch thay i lp n mc c th. Khng lm dng friend

Ton t new
Xem xt lnh sau
Time *timePtr; timePtr = new Time;

Ton t new
To i tng vi kch thc vng nh kiu Time Thnh cng : tr v con tr tr n vng nh Li (nu khng b nh, ) : tr v 0 Gi hm to mc nh cho i tng Tr v con tr kiu Time

Cung cp b khi to
double *ptr = new double( 3.14159 ); Time *timePtr = new Time( 12, 0, 0 );

Cp pht mng
int *gradesArray = new int[ 10 ];

Ton t delete
Gii phng vng nh c cp pht ng cho i tng Gi hm hy cho i tng Gii phng vng nh dnh cho i tng Vng nh c th dng cp pht li cho cc i tng khc Gii phng mng delete [] gradesArray; Gii phng mng gradesArray ang tr ti Nu l mng i tng u tin gi hm hy cho tng i tng Sau gii phng vng nh V d
delete timePtr;

Ton t phm vi
Ton t :: dng xc nh chnh xc hm
(thuc tnh) c truy xut thuc lp no. Cu lnh: pt.OffsetPt(2,2); <=> pt.Point::OffsetPt(2,2); Cn thit trong mt s trng hp:
Cch gi hm trong tha k. Tn thnh vin b che bi bin cc b. V d: Point(int xVal, int yVal) {
Point::xVal = xVal; Point::yVal = yVal; }

Danh sch khi to thnh vin


Tng ng vic gn gi tr d liu thnh vin.
class Point { int xVal, yVal; public: Point (int x, int y) { xVal = x; yVal = y; } // }; class Image { public: Image(const int w, const int h); private: int width; int height; //... }; Image::Image(const int w, const int h) { width = w; height = h; //..................... } Image::Image (const int w, const int h) : width(w), height(h) { //............... }

Point::Point (int x, int y) : xVal(x), yVal(y) { }

Thnh vin hng


Hng d liu thnh vin:
class Image { public: Image(const int w, const int h); private: const int width; const int height; //... }; Khai bo bnh thng nh d liu thnh vin

Khi to SAI

class Image { const int width = 256; const int height = 168; //... }; Khi to NG thng qua danh sch khi to thnh vin

Image::Image (const int w, const int h) : width(w), height(h) { //................ }

Thnh vin hng


Hng i tng: khng c thay i gi tr. Hm thnh vin hng:
c php gi trn hng i tng. Khng c thay i gi tr d liu thnh vin.
class Set { public: Set(void){ card = 0; } bool Member(const int) const; void AddElem(const int); //... }; bool Set::Member (const int elem) const { //... } void main() { const Set s; s.AddElem(10); // SAI s.Member(10); // ok }

Thnh vin tnh


D liu thnh vin tnh:
Dng chung 1 bn sao chp (1 vng nh) chia s cho tt c i tng ca lp . S dng: <TnLp>::<TnDLiuThnhVin> Thng dng m s lng i tng.
class Window { // danh sch lin kt tt c Window static Window *first; // con tr ti window k tip Window *next; //... }; Window *Window::first = &myWindow; // . Khai bo

Khi to d liu thnh vin tnh

Thnh vin tnh


D liu thnh vin tnh
D liu cp lp Thuc tnh ca lp, khng phi ca 1 i tng no ca lp. Hiu qu khi ch cn 1 bin cho lp l C v nh bin ton cc, nhng ch c phm vi lp Ch cc i tng thuc lp mi c th truy cp Cn khi to 1 ln duy nht Tn ti ngay c khi khng c i tng no ca lp tn ti, khng ph thuc vo bt k i tng no C th l public, private hoc protected

Thnh vin tnh


Hm thnh vin tnh:
Tng ng vi hm ton cc. Gi thng qua: <TnLp>::<TnHm>
class Window { // . static void PaintProc () { .. } // }; Khai bo nh ngha hm thnh vin tnh

void main() { // . Window::PainProc();


}

Truy xut hm thnh vin tnh

Thnh vin tnh


Hm thnh vin tnh
Cc hm static khng c con tr this Cc d liu v hm thnh vin static tn ti m khng ph thuc vo cc i tng C th gi hm static ngay c khi khng c i tng no ca lp tn ti C th s dng mt hm thnh vin static truy vn mt i tng tm ra n l i tng no. C ch trong vic g ri mt chng trnh gia nhng tnh hung khc nhau

Truy xut cc d liu static


V d: class NGUOI
float tn; //thu nhp tng ngi static int tongsn; //tng s ngi c trong class static float tongtn;//tng thu nhp ca cc object public: } nguoi1, nguoi2; {

Truy xut tongtn:


nguoi1.tongtn nguoi2.tongtn NGUOI::tongtn // c th dng c khi cha c i tng no

nguoi1.tn, nguoi2.tn s chim 2 vng nh khc nhau nguoi1.tongtn, nguoi2. tongtn chim cng 1 vng nh

Thnh phn static ca lp


1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. #include <iostream.h> #include <new.h> // C++ standard new operator #include <string.h> class Employee { char *firstName; char *lastName; // static data member static int count; // number of objects instantiated public: Employee( const char *, const char * ); // constructor ~Employee(); // destructor const char *getFirstName() const; // return first name const char *getLastName() const; // return last name // static member function static int getCount(); // return # objects instantiated }; // end class Employee

17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35.

int Employee::count = 0; int Employee::getCount() { return count; } Employee::Employee( const char *first, const char *last ) { firstName = new char[ strlen( first ) + 1 ]; strcpy( firstName, first ); lastName = new char[ strlen( last ) + 1 ]; strcpy( lastName, last ); ++count; // increment static count of employees cout << "Employee constructor for " << firstName << ' ' << lastName << " called." << endl; } // end Employee constructor Employee::~Employee() { cout << "~Employee() called for " << firstName << ' ' << lastName << endl; delete [] firstName; delete [] lastName; --count; // decrement static count of employees }

36. 37.

38. 39. 40. 41.

42. 43.

const char *Employee::getFirstName() const { // const before return type prevents client from // modifying private data; client should copy returned // string before destructor deletes storage to prevent // undefined pointer return firstName; } // end function getFirstName const char *Employee::getLastName() const { // const before return type prevents client from // modifying private data; client should copy returned // string before destructor deletes storage to prevent // undefined pointer return lastName; } // end function getLastName

void main() { cout << "Number of employees before instantiation is " << Employee::getCount() << endl; // use class name Employee *e1Ptr = new Employee( "Susan", "Baker" ); Employee *e2Ptr = new Employee( "Robert", "Jones" ); cout << "Number of employees after instantiation is " << e1Ptr->getCount(); cout << "\n\nEmployee 1: << e1Ptr->getFirstName() << " " << e1Ptr->getLastName() << "\nEmployee 2: << e2Ptr->getFirstName() << " " << e2Ptr->getLastName() << "\n\n"; delete e1Ptr; // recapture memory e1Ptr = 0; // disconnect pointer from free-store space delete e2Ptr; // recapture memory e2Ptr = 0; // disconnect pointer from free-store space cout << "Number of employees after deletion is " << Employee::getCount() << endl; } // end main

Number of employees before instantiation is 0 Employee constructor for Susan Baker called. Employee constructor for Robert Jones called. Number of employees after instantiation is 2

Employee 1: Susan Baker Employee 2: Robert Jones


~Employee() called for Susan Baker ~Employee() called for Robert Jones Number of employees after deletion is 0

Thnh vin tham chiu


Tham chiu d liu thnh vin:
class Image { int width; int height; int &widthRef; //... };
class Image { int width; int height; int &widthRef = width; //... }; Khi to NG thng qua danh sch khi to thnh vin Khai bo bnh thng nh d liu thnh vin

Khi to SAI

Image::Image (const int w, const int h) : widthRef(width) { //... }

Thnh vin l i tng ca 1 lp


D liu thnh vin c th c kiu:
D liu (lp) chun ca ngn ng. Lp do ngi dng nh ngha (c th l chnh lp ).
class Point { . }; class Rectangle { public: Rectangle (int left, int top, int right, int bottom); //... private: Point topLeft; Point botRight; }; Rectangle::Rectangle (int left, int top, int right, int bottom) : topLeft(left,top), botRight(right,bottom) {}

Khi to cho cc d liu thnh vin qua danh sch khi to thnh vin

Mng cc i tng
S dng hm to khng i s (hm to mc nhin - default constructor).
VD: Point pentagon[5];

S dng b khi to mng:


VD: Point triangle[3] = { Point(4,8), Point(10,20), Point(35,15) }; Ngn gn: Set s[4] = { 10, 20, 30, 40 }; tng ng vi: Set s[4] = { Set(10), Set(20), Set(30), Set(40) };

Mng cc i tng
S dng dng con tr:
Cp vng nh: VD: Point *pentagon = new Point[5]; Thu hi vng nh: delete[] pentagon; delete pentagon; // Thu hi vng nh u
class Polygon { public: //... private: Point *vertices; int nVertices; }; Khng cn bit kch thc mng. // cc nh // s cc nh

Phm vi lp
Thnh vin trong 1 lp:
Che cc thc th trng tn trong phm vi.
// int fork (void); // fork h thng class Process { int fork (void); // fork thnh vin //... }; // int Process::func1 (void) { int x = fork(); // gi fork cc b int pid = ::fork(); // gi hm fork h thng //... }

fork thnh vin che i fork ton cc trong phm vi lp Process

Phm vi lp
Lp ton cc: i a s lp trong C++. Lp lng nhau: lp cha ng lp. Lp cc b: trong 1 hm hoc 1 khi.
class Rectangle { // Lp lng nhau public: Rectangle (int, int, int, int); //.. private:
class Point { public: Point(int a, int b) { } private: int x, y; };

Point topLeft, botRight; }; Rectangle::Point pt(1,1); // sd ngoi

void Render (Image &i) { class ColorTable { public: ColorTable () { /* ... */ } AddEntry (int r, int g, int b) { /* ... */ } //... }; ColorTable colors; //... } ColorTable ct; // SAI

Cu trc v hp
Cu trc (structure):
Bt ngun t ngn ng C. Tng ng vi class vi cc thuc tnh l public. S dng nh class.
struct Point { Point (int, int); void OffsetPt(int, int); int x, y; }; class Point { public: Point(int, int); void OffsetPt(int, int); int x, y; };

Point p = { 10, 20 };

C th khi to dng ny nu khng c nh ngha hm xy dng

Cu trc v hp
Hp (union):
Tt c thnh vin nh x n cng 1 a ch bn trong i tng chnh n (khng lin tip). Kch thc = kch thc ca d liu ln nht.
union Value { long double char Pair //... }; class Pair { Value Value //... };

integer; real; *string; list;

class Object { private: enum ObjType {intObj, realObj, strObj, listObj}; ObjType type; // kiu i tng Value val; // gi tr ca i tng //... };

*head; *tail;

Kch thc ca Value l 8 bytes = sizeof(double)

Cc trng bit
iu khin i tng mc bit. VD: Truy xut cc bit trong header ca gi tin.
typedef unsigned int Bit; class Packet { Bit type : 2; // rng 2 bit Bit acknowledge : 1; // rng 1 bit Bit channel : 4; // rng 4 bit Bit sequenceNo : 4; // rng 4 bit Bit moreData : 1; // rng 1 bit //... }; enum PacketType { dataPacket, controlPacket, supervisoryPacket }; enum Bool { false, true };

// Packet p; p.type = controlPacket; p.acknowledge = true;

Qu ti (Overloading)

Qa ti hm
nh ngha cc hm cng tn i s phi khc nhau:
S lng Th t Kiu
class Time { //... long GetTime (void); // s giy tnh t na m void GetTime (int &hours, int &minutes, int &seconds); }; void main() { int h, m, s; long t = GetTime(); // Gi hm ??? GetTime(h, m, s); // Gi hm ??? }

C th dng i s mc nh.

Qu ti ton t
nh ngha li cc php ton trn i tng. Cc php ton c th ti nh ngha:
+ * ! ~ & ++ -() -> ->*

Mt ngi

new +

delete += != * -= < / /= > % %= <= & &= >= | |= && ^ ^= || <<


<<=

>>
>>=

Hai ngi

= ==

[]

()

Cc php ton khng th ti nh ngha:


. .* :: ?: sizeof

Qu ti ton t
Bng hm thnh vin:
class Point { public: Point (int x, int y) { Point::x = x; Point::y = y; } Point operator + (Point &p) { return Point(x + p.x,y + p.y); } Point operator - (Point &p) { return Point(x - p.x, y - p.y); } private: int x, y; }; C 1 tham s (Nu l ton t hai ngi) void main() { Point p1(10,20), p2(10,20); Point p3 = p1 + p2; Point p4 = p1 - p2; Point p5 = p3.operator + (p4); Point p6 = p3.operator (p4); };

Qu ti ton t
Bng hm c lp: thng khai bo friend
class Point { public: Point (int x, int y) { Point::x = x; Point::y = y; } friend Point operator + (Point &p, Point &q) {return Point(p.x + q.x,p.y + q.y); } friend Point operator - (Point &p, Point &q) {return Point(p.x - q.x,p.y - q.y); } private: C 2 tham s int x, y; (Nu l ton t hai ngi) };

void main() { Point p1(10,20), p2(10,20); Point p3 = p1 + p2; Point p4 = p1 - p2; Point p5 =operator + (p3, p4); Point p6 = operator (p3, p4); };

Chuyn kiu
Mun thc hin cc php cng:
void main() { Point p1(10,20), p2(30,40), p3, p4, p5; p3 = p1 + p2; p4 = p1 + 5; p5 = 5 + p1; };

C th nh ngha thm 2 ton t:


class Point { //... friend Point operator + (Point, Point); friend Point operator + (int, Point); friend Point operator + (Point, int); };

Chuyn kiu (tt)


Chuyn i kiu: ngn ng nh ngha sn.
void main() { Point p1(10,20), p2(30,40), p3, p4, p5; p3 = p1 + p2; p4 = p1 + 5; // tng ng p1 + Point(5) p5 = 5 + p1; // tng ng Point(5) + p1 }

nh ngha php chuyn i kiu


class Point { //... Point (int x) { Point::x = Point::y = x; } friend Point operator + (Point, Point); }; Chuyn kiu 5 Point(5)

Qu ti ton t xut <<


nh ngha hm ton cc:
ostream& operator << (ostream&, Class&);
class Point { public: Point (int x=0, int y=0) { Point::x = x; Point::y = y; } friend ostream& operator << (ostream& os, Point& p) { os<< ( << p.x << , << p.y << ); } // .. private: int x, y; }; void main() { Point p1(10,20), p2; cout<<Diem P1: << p1 << endl; cout<<Diem P2: << p2 << endl; }

Kt qu trn mn hnh ?

Qu ti ton t nhp >>


nh ngha hm ton cc:
istream& operator >> (istream&, Class&);
class Point { public: Point (int x=0, int y=0) { Point::x = x; Point::y = y; } friend istream& operator >> (istream& is, Point& p) { cout<<Nhap x: ; is>>p.x; cout<<Nhap y: ; is>>p.y; } // .. private: int x, y; }; void main() { Point p1, p2; cout<<Nhap thong tin cho P1: \n; cin>>p1; cout<<Nhap thong tin cho P2: \n; cin>>p2; }

Qu ti ton t [ ]
Thng thng xut ra gi tr ca 1 phn t ti v tr cho trc trong i tng. nh ngha l hm thnh vin.
class StringVec { public: StringVec (const int dim); ~StringVec (); char* operator [] (int); int add(char* ); // .. private: char **elems; // cac phan tu int dim; // kich thuoc cua vecto int used; // vi tri hien tai }; char* StringVec::operator [] (int i) { if ( i>=0 && i<used) return elems[i]; return ; } void main() { StringVec sv1(100); sv1.add(PTPhi);sv1.add(BQThai); sv1.add(LVLam); sv1.add(NCHuy); cout<< sv1[2]<<endl; cout<<sv1[0]; }

Qu ti ton t ()
nh ngha l hm thnh vin.
class Matrix { public: Matrix (const short rows, const short cols); ~Matrix (void) {delete elems;} double& operator () (const short row, const short col); friend ostream& operator << (ostream&, Matrix&); friend Matrix& operator + (Matrix&, Matrix&); friend Matrix& operator - (Matrix&, Matrix&); friend Matrix& operator * (Matrix&, Matrix&); private: const short rows; // s hng const short cols; // s ct double *elems; // cc phn t }; double& Matrix::operator () (const short row, const short col) { static double dummy = 0.0; return (row >= 1 && row <= rows && col >= 1 && col <= cols) ? elems[(row - 1)*cols + (col - 1)] : dummy; } void main() { Matrix m(3,2); m(1,1) = 10; m(1,2) = 20; m(2,1) = 30; m(2,2) = 40; m(3,1) = 50; m(3,2) = 60; cout<<m<<endl; }

Qu ti ton t ++ & - Ton t ++ (hoc ton t --) c 2 loi:


Tin t: ++n Hu t: n++
class PhanSo { int tuso, mauso; public: void main() { PhanSo p1(3,4), p2; cout<< p1++; cout<<++p2; cout<<++(p1++) + (++p2)++; }

// .. PhanSo(int x=0 , int y=1) {tuso=x; mauso=y}; friend PhanSo operator ++ (PhanSo&); friend PhanSo operator ++ (PhanSo&, int);

}; PhanSo operator ++ (PhanSo& p) { return (p = PhanSo(p.tuso+p.mauso, p.mauso)); } PhanSo operator ++ (PhanSo& p, int notused) { PhanSo p2 = PhanSo(p.tuso+p.mauso, p.mauso); return p2; }

Kt qu trn mn hnh ?

Qu ti new & delete


Hm new v delete mc nh ca ngn ng:
Nu i tng kch thc nh, c th s gy ra qu nhiu khi nh => chm. Khng ng k khi i tng c kch thc ln.

=> Ton t new v delete t c qu ti. nh ngha theo dng hm thnh vin:
class Point { public: //... void* operator new (size_t bytes); void operator delete (void *ptr, size_t bytes); private: int xVal, yVal; }; void main() { Point *p = new Point(10,20); Point *ds = new Point[30]; // delete p; delete []ds; }

Tha k (Inheritance)

Khi nim
K tha t cc lp c t trc. ch li: c th tn dng li
Cc thuc tnh chung Cc hm c thao tc tng t
Lp c s (Base class) LP CHA (Super class) STUDENT

Lp dn xut (Derived class)

LP CON (Sub class)

ENT_STUDENT

V d minh ha
K hiu composition ContactDir
n

Contact

#include <iostream.h> #include <string.h> class Contact { private: char *name; // ten doi tac char *address; // dia chi doi tac char *tel; // so dien thoai public: Contact (const char *name, const char *address, const char *tel); ~Contact (); const char* Name () const { return name;} const char* Address() const { return address;} const char* Tel() const { return tel;} friend ostream& operator << ( ostream&, Contact& ); };

class ContactDir { private: int Lookup(const char *name); Contact **contacts; int dirSize; // ds cac doi tac // kich thuoc thu muc hien tai

int maxSize; // kich thuoc thu muc toi da public: ContactDir (const int maxSize); ~ContactDir(); void Insert(const Contact&); void Delete(const char *name); Contact* Find(const char *name); friend ostream& operator << (ostream&, ContactDir&); // };

V d minh ha (tt)
ContactDir K hiu Tha k SmartDir
class SmartDir : public ContactDir { private: char public: SmartDir(const int max) : ContactDir(max) *recent; // ten duoc tim gan nhat } Contact* SmartDir::Find (const char *name) { Contact *c = ContactDir::Find(name); if (c != 0) recent = (char*) c->Name(); return c; } Contact* SmartDir::Recent (void) { return recent == 0 ? 0 : ContactDir::Find(recent); n

Contact

{ recent = 0; }
Contact* Recent (void); Contact* Find (const char *name); // . };

V d (tt) - m t trong b nh
**contacts dirSize maxSize **contacts dirSize maxSize *recent

ContactDir
*contacts 1

SmartDir
*contacts 1

Contact 1

*contacts 2
*contacts 3

Contact 1

*contacts 2
*contacts 3

Contact 2
*contacts i

Contact 2
*contacts i

Contact i

*contacts n

Contact i

*contacts n

Hm to v hm hy
Trong tha k, khi khi to i tng:
Hm to ca lp cha s c gi trc Sau mi l hm to ca lp con.

Trong tha k, khi hy b i tng:


Hm hy ca lp con s c gi trc Sau mi l hm hy ca lp cha.
A

Hm to v hm hy (tt)
class SmartDir : public ContactDir { private: char *recent; // ten duoc tim gan nhat public: SmartDir(const int max) : ContactDir(max) { recent = 0; } SmartDir(const SmartDir& sd): ContactDir(sd) { recent = 0; } ~SmartDir() { delete recent; } // . }; Thu hi vng nh ca con tr thnh vin ca lp con nu cp vng nh trong hm to. Gi hm to ca lp cha

Thnh vin lp c bo v
Tha k:
C tt c cc d liu v hm thnh vin. Khng c truy xut n thnh vin private.

Thuc tnh truy cp protected:


Cho php lp con truy xut.
class ContactDir {
//... protected: int Lookup (const char *name); Contact **contacts; // ds cac doi tac class Foo { public: // cac thanh vien chung... private: // cac thanh vien rieng... protected: // cac thanh vien duoc bao ve... public: // cac thanh vien chung nua... protected: // cac thanh vien duoc bao ve nua... };

int
};

dirSize;

// kich thuoc hien tai


// kich thuoc toi da

int maxSize;

Lp c s ring, chung v c bo v
Lp c s Tha k public Tha k private Tha k protected

private
public protected
class A { private:

_
public protected

_
private private

_
protected protected

int x; void Fx (void);

public:
int y; void Fy (void); protected: int z; void Fz (void);

};

class B : A { // Tha k dng private . }; class C : private A { // A l lp c s ring ca B }; class D : public A { // A l lp c s chung ca C }; class E : protected A { // A: lp c s c bo v . };

a tha k
OptionList Window
class OptionList { public: OptionList (int n); ~OptionList (); //... }; class Window { public: Window (Rect &); ~Window (void); //... };

Menu

OptionList object OptionList data members

Window object Window data members

Menu object OptionList data members

Window data members Menu data members

class Menu : public OptionList, public Window { public: Menu (int n, Rect &bounds); ~Menu (void); //... }; Menu::Menu (int n, Rect &bounds) : OptionList(n), Window(bounds) { /* ... */ }

S m h trong a tha k
class OptionList { public: // void Highlight (int part); }; class Window { public: // void Highlight (int part); };

class Menu : public OptionList,


public Window { . }; void main() { Menu m1(.);

Hm cng tn

Ch r hm ca lp no

void main() {
x l

Gi hm ca lp no ?

Menu m1(.); m1.OptionList::Highlight(10); m1.Window::Highlight(20); .

m1.Highlight(10);
. }

Chuyn kiu
C sn 1 php chuyn kiu khng tng minh:
i tng lp cha = i tng lp con; p dng cho c i tng, tham chiu v con tr.
m Menu Window Window Window m(n, bounds); win = m; &wRef = m; *wPtr = &menu; win Window data members
OptionList data members Window data members Menu data members

Khng c thc hin php gn ngc:


i tng lp con = i tng lp cha; // SAI
Nu mun thc hin phi t nh ngha php p kiu

class Menu : public OptionList, public Window { public: //... Menu (Window&); };

V d
#include <iostream.h> class base { int x; public: void setx(int i) { x=i; } int getx() { return x; } }; class derived: public base { int y; public: void sety(int i) { y=i; } int gety() { return y; } };

main() { base *p, b_ob; derived *d,d_ob; p=&b_ob; p->setx(10); p->sety(20); //? cout <<"Base object x: "<<p->getx()<<"\n"; cout <<"Derived object y: "<<p->gety()<<"\n"; p=&d_ob; p->setx(150); p->sety(100); //? cout <<"Base object x: "<<p->getx()<<"\n"; cout <<"Derived object y: "<<p->gety()<<"\n"; d=&b_ob; //? d->setx(200); d->sety(250); cout <<"Base object x: "<<d->getx()<<"\n"; cout <<"Derived object y: "<<d->gety()<<"\n"; d=&d_ob; d->sety(300); d->setx(400); //?? cout <<"Derived object y: "<<d->gety()<<"\n"; cout <<"Base object x: "<<d->getx()<<"\n"; }

Hm o
Lin kt tnh (static binding):
Xc nh khi bin dch chng trnh. Dng hm thnh vin. Gi hm ca lp c s (lp cha).
class ContactDir { //... public: int Lookup (const char *name); //... }; class SortedDir : public ContactDir { public: SortedDir(const int max) : ContactDir(max) {} int Lookup(const char *name); }; cout<<p->Lookup(ABC); .

void () voidmain main (){ { u? ContactDir ContactDir c1(10); *p; SortedDir p = &c1; } SortedDir *p; c1(10); p = &c1;

Li

Gi hm no ?

Hm o (tt)
Lin kt ng (dynamic binding)
Xc nh khi thc thi chng trnh. Dng hm o (virtual function). Gi hm ca lp dn xut (lp con). Th hin tnh a hnh ca OOP.
void main() { ContactDir c1(10); SortedDir *p1; p1 = &c1; p1->Lookup(ABC);
SortedDir c2(20); ContactDir *p2; p2 = &c2; p2->Lookup(ABC); }

class ContactDir { //... public: virtual int Lookup (const char *name); }; class SortedDir : public ContactDir { B t kha //. virtual th kt public: int Lookup(const char *name); qu l gi? };

Gi hm ca lp no ?

SAI

Kt qu trn mn hnh l g?

#include <iostream.h> class base{ public: int i; base(int x) {i=x;} virtual void func() { cout <<"Ham func() cua lop co so, i= "<<i<<endl; } }; class derived1:public base{ public: derived1(int x):base(x) {} virtual void func() { cout <<"Ham func() cua lop dan suat 1, i= "<<2*i<<endl; } }; class derived2:public base{ public: derived2(int x):base(x) {} }; Kt qu l main() { gi? base *b; base ob(10); derived1 d_ob1(10); derived2 d_ob2(10); b=&ob; b->func(); b=&d_ob1; b->func(); b=&d_ob2; b->func(); getchar(); }

Lp c s o
S m h - d tha d liu
class OptionList : public Widget, List { /*...*/ }; class Window : public Widget, Port { /*...*/ }; class Menu : public OptionList,

public Window
{ /*...*/ };

i tng Menu

Lp c s o (tt)
Cch x l: dng lp c s o.
class OptionList : virtual public Widget, public List { /*...*/ }; class Window : virtual public Widget, public Port Ch c 1 i tng Widget

{ /*...*/ };
class Menu : public OptionList, public Window { /*...*/ }; Menu::Menu (int n, Rect &bounds) : Widget(bounds), OptionList(n), Window(bounds) { //... }

#include <iostream.h> class base{ public: int i; }; class derived1:public base{ public: int j; }; class derived2:public base{ public: int k; }; class derived3:public derived1, public derived2{ public: int tich() { return i*j*k; } }; main() { derived3 ob; ? i ca M h, ob.i=10; lp no? ob.j=20; ob.k=30; cout <<"tich so la : "<<ob.tich ()<<endl; getchar(); }

#include <iostream.h> class base{ public: int i; }; class derived1: virtual public base{ public: int j; }; class derived2: virtual public base{ public: int k; }; class derived3:public derived1, public derived2{ public: int tich() { return i*j*k; } }; main() { derived3 ob; ob.i=10; ob.j=20; ob.k=30; cout <<"tich so la : "<<ob.tich ()<<endl; getchar(); }

You might also like