Professional Documents
Culture Documents
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.
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
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.
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
Tru tng ha
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
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.
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.
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.
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
TN LP
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); ..
Khai bo Lp
Gi hm trn i tng
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 .
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;
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
class Point { int xVal, yVal; public: void SetPt (int, int); void OffsetPt (int, int); };
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; }
};
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
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); . }
};
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 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
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); }
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; }
Cc hm khc hot ng trn con tr ny Hm khng tr v tham chiu phi c gi sau cng
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]; }
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; };
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; }
Khi to SAI
class Image { const int width = 256; const int height = 168; //... }; Khi to NG thng qua danh sch khi to thnh vin
nguoi1.tn, nguoi2.tn s chim 2 vng nh khc nhau nguoi1.tongtn, nguoi2. tongtn chim cng 1 vng nh
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.
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
Khi to SAI
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];
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 //... }
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; };
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 };
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 //... };
class Object { private: enum ObjType {intObj, realObj, strObj, listObj}; ObjType type; // kiu i tng Value val; // gi tr ca i tng //... };
*head; *tail;
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 };
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 +
>>
>>=
Hai ngi
= ==
[]
()
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; };
Kt qu trn mn hnh ?
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; }
// .. 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 ?
=> 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
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.
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.
int
};
dirSize;
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
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
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); };
Hm cng tn
Ch r hm ca lp no
void main() {
x l
Gi hm ca lp no ?
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
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(); }