friend void SetToReal IntSet &, RealSet&; private: int elems[maxCard]; int card; }; class RealSet RealSet { public: //.... friend class IntSet; };.
Trang 1L P TRÌNH
CLASS & OBJECT
tuantp@hcmup.edu.vn http://giaotrinh.tranphuoctuan.com
T.P.TU N - LTH T 2
9/6/2009
nh ngh a: tên l p, thu c tính, ph ng th c Cài t ph ng th c
m b o tính úng n c a d li u Các thành ph n, ph m vi truy c p
2 Th vi n hóa
3 M t ví d
4 Thi t k l p
Xác nh thành ph n d li u Xác nh thành ph n x lý
5 Các ph c ph ng th ng th c/hàm c bi t
Constructor Destructor
T.P.TU N - LTH T 3
p: ki u d li u tr u t ng.
TÊN L P
li u thành viên
Hàm thành viên
c t
i
ng
p các
thao tác
class TÊNL P [ : < Quy n truy xu t > L PCHA PCHA ]
{ < Quy n truy xu t > :
DataType1 memberdata1;
DataType2 memberdata2;
……….
< Quy n truy xu t > :
memberFunction1();
memberFunction2();
…………
};
private protected public
T.P.TU N - LTH T 4
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);
……
pt.xVal = 10; // úng hay sai?
Point pt1, pt2, pt3;
……….
}
i hàm trên
i t ng
o ra
i t ng thu c l p Point
Khai báo p
nh ngh a các hàm thành viên
Trang 2T.P.TU N - LTH T 5
9/6/2009
T.P.TU N - LTH T 6
9/6/2009
Tên l p Các thu c tính các thành ph n d li u a l p
Các ph ng th c
các thao tác (hàm) tác ng t i d li u c a
i t ng
class Student
{
public:
char name[30];
int id;
};
void main()
{
Student s1;
cin >> s1.name;
cin >> s1.id;
}
thu c tính
i t ng
void printStudent( Student s ) {
cout << ”name: ” << s.name << endl;
cout << ”id: ” << s.id << endl;
}
void main() {
Student s;
printStudent(s);
}
Trang 3T.P.TU N - LTH T 9
9/6/2009
1 L p và i t ng - Ph Ph ng ng th c
T.P.TU N - LTH T 10
9/6/2009
class Student {
public:
char name[30];
int id;
void print();
};
void Student::print () {
cout << ”name: ” << name << endl;
cout << ”id: ” << id << endl;
}
prototype a
ph ng th c
void main() {
Student s; cin >> s.name; cin >> s.id;
s.print();
}
T.P.TU N - LTH T 11
Hàm inline :
i thi n t c th c thi
n b nh (dành cho mã l nh) khi th c thi.
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;
public : void SetPt (int x, int y) { xVal = x;
yVal = y;
} void OffsetPt (int x, int y) { xVal += x;
yVal += y;
} };
Cách 2 ch 2:
nh ngh a bên trong p
Cách 1 ch 1:
thêm
khóa
inline
T.P.TU N - LTH T 12
Ph n l n l i l p trình là do thao tác sai v i
li u
li u không h p l (sai mi n giá tr )
li u không th ng nh t
Trang 4T.P.TU N - LTH T 13
9/6/2009
Date.h:
class Date
{
public:
int y, m, d;
bool set(int yy,int mm,int dd);
};
T.P.TU N - LTH T 14
9/6/2009
date.cpp:
#include ”date.h”
bool Date::set(int yy, int mm, int dd) {
// ki m tra tính h p l a tham s
#include ”date.h”;
void main() {
Date d1, d2;
d1.set(2000, 13, 32 ); d2.set( 2001, 2, 29 ); }
myCalendar.cpp:
#include ”date.h”;
void main()
{
Date d1, d2;
d1.y = 2001;
d1.m = 2;
d1.d = 29;
}
u truy c p tr c
ti n các thu c tính thì v n không
ki m soát c
thu c tính
Truy v n và c p nh t thu c tính thông qua
giao di n th c s a l i t ng
ki m soát tính h p l khi thay i giá tr
Trang 5T.P.TU N - LTH T 17
9/6/2009
Date.h:
class Date
{
public:
int getYear();
int getMonth();
int getDay();
bool set(int, int, int);
void print();
void copyTo(Date&);
bool equalTo(Date&);
private:
int y, m, d;
};
Giao di n
óng gói/che d u thông tin
T.P.TU N - LTH T 18
9/6/2009
date.cpp:
#include ”date.h”;
bool Date::set(int yy, int mm, int dd) {
// ki m tra tính h p l a tham s
} int Date::getYear() {
return y;
}
óng gói/che d u thông tin
T.P.TU N - LTH T 19
myCalendar.cpp:
#include ”date.h”;
void main()
{
Date d1, d2;
if (d1.set(2000, 1, 31))
cout << d1.getYear() << endl;
else cout << ”ngay thang khong hop le”;
cout << d1.m; // compile error
d1.d = 30; // compile error
}
óng gói/che d u thông tin
T.P.TU N - LTH T 20
di n (ch c n ng, cách dùng); không c n
ng
óng gói/che d u thông tin
Trang 6T.P.TU N - LTH T 21
9/6/2009
Các thành ph n public
Ph ng th c trong l p
Ph ng th c p k th a
Ph ng th c ngoài l p
Các thành ph n protected
Ph ng th c trong l p
Ph ng th c p k th a
Các thành ph n private
Ph ng th c trong l p
T.P.TU N - LTH T 22
9/6/2009
x x x
TRONG
X
NGOÀI
x x
public
x x
protected
x
private
i Truy
C p Thành
Ph n
Ph m vi truy c p
2 Th vi n hóa
nhau
p
Date.h:
#if !defined (_DATE_H )
#define _DATE_H
//khai báo th vi n
#include <iostream.h>
class Date {
private:
int y, m, d;
public:
void set(int yy, int mm, int dd);
void print();
};
#endif
Trang 7T.P.TU N - LTH T 25
9/6/2009
Date.cpp:
#include ”Date.h”
void Date::set(int yy, int mm, int dd)
{
}
void Date::print()
{
cout <<d<<“/”<<m<<“/”<<y<<endl;
}
T.P.TU N - LTH T 26
9/6/2009
myApp.cpp:
#include <iostream.h>
#include ”Date.h”
void main() {
Date ngaysinh;
ngaysinh.set(2007, 3, 8);
ngaysinh.print();
}
T.P.TU N - LTH T 27
3 M t ví d - L p Set (t p h p)
#include <iostream.h>
const maxCard = 100;
enum Bool {false, true};
class Set Set {
private:
int elems[maxCard];
int card;
public:
void EmptySet(){ card = 0; }
Bool IsMember (const int);
void AddElem (const int);
void RmvElem (const int);
void Copy (Set&);
Bool Equal (Set&);
void Intersect (Set&, Set&);
void Union (Set&, Set&);
void Print ();
};
Bool Set::IsMember (const int elem) { for (register i = 0; i < card; ++i)
if (elems[i] == elem) return true;
return false;
} void Set::AddElem (const int elem) {
if (IsMember(elem)) return;
if (card < maxCard) elems[card++] = elem;
else cout << "Set overflow“<<endl;
} void Set::RmvElem (const int elem) { for (register i = 0; i < card; ++i)
if (elems[i] == elem) { for (; i < card-1; ++i) // D ch elems[i] = elems[i+1];
card;
} }
T.P.TU N - LTH T 28
void Set::Copy (Set &set) { for (register i = 0; i < card; ++i) set.elems[i] = elems[i];
set.card = card;
} Bool Set::Equal (Set &set) {
if (card != set.card) return false;
for (register i = 0; i < card; ++i)
if (!set.IsMember(elems[i])) return false;
return true;
} void Set::Print (void) { cout << "{";
for (int i = 0; i < card-1; ++i) cout << elems[i] << ",";
if (card > 0) cout << elems[card-1];
cout << "}“<<endl;
}
………
int main (void) { Set s1, s2;
s1.EmptySet(); s2.EmptySet();
s1.AddElem(10); s1.AddElem(20);
s1.AddElem(30); s1.AddElem(40);
s2.AddElem(30); s2.AddElem(50);
s2.AddElem(10); s2.AddElem(60);
cout << "s1 = "; s1.Print();
cout << "s2 = "; s2.Print();
s2.RmvElem(50);
cout << "s2 - {50} = ";
s2.Print();
if (s1.IsMember(20)) cout << "20 is in s1\n";
if (!s1.Equal(s2)) cout << "s1 <> s2\n";
return 0;
}
K t
qu ?
3 M t ví d - L p Set (t p h p)
Trang 8T.P.TU N - LTH T 29
9/6/2009
o l p Student
có các thu c tính tên, mã sinh viên, m
trung bình
th p.
T.P.TU N - LTH T 30
9/6/2009
Nhóm kh i t o Nhóm truy v n thông tin Nhóm c p nh t thông tin Nhóm x lý tính toán Nhóm ki m tra ràng bu c
ng thu c l p này
trong ph m vi protected hay private
Nhóm kh i t o
Ví d :
KhoiTaoPS (tu=0,mau=1) KhoiTaoSV (ten=“”,…) DSLK (Head=Tail=NULL)
….
Trang 9T.P.TU N - LTH T 33
9/6/2009
Có nhi u lo i câu h i truy v n có th :
truy v n n gi n (“giá tr a x là bao nhiêu?”)
truy v n u ki n (“thành viên x có l n h n 10
không?”)
truy v n d n xu t (“t ng giá tr a các thành viên x
và y là bao nhiêu?”)
ng
T.P.TU N - LTH T 34
9/6/2009
i v i các truy v n n gi n, quy c t tên
ph ngth c: ti n t “get”, ti p theo là tên c a thành viên
int getX();
int getSize();
Các lo i truy v n khác nên có tên có tính mô t Truy v n u ki n nên có ti n t “is”
T.P.TU N - LTH T 35
p nh t thông tin
p nh t là gán m t giá tr nào ó cho m t
thành viên d li u
tên: dùng ti n t “set” kèm theo tên thành viên
n s a
int setX(int);
T.P.TU N - LTH T 36
i gì?
Ngoài vi c b o v các nguyên t c óng gói, ta
li u có h p l hay không.
Cho phép ch các d li u có th truy v n hay thay
Trang 10T.P.TU N - LTH T 37
9/6/2009
int Student::setGPA(double newGPA)
{
if ((newGPA >= 0.0) && (newGPA <= 4.0))
{
this->gpa = newGPA;
return 0; // Return 0 to indicate success }
else
{
return -1; // Return -1 to indicate failure }
}
T.P.TU N - LTH T 38
9/6/2009
Nhóm x lý tính toán
cung c p thông tin t ng h p t các thu c tính
Ví d :
NhanVien.TinhLuong() SinhVien.XepLoai() Nghiem PhuongTrinh.GiaiPhuongTrinh() Giatri PhanSo.TinhGiaTri()
…
Nhóm ki m tra ràng bu c
Ki m tra tính úng ng c a d li u
Ví d :
Ngày tháng n m h p l
Ngày vào làm và ngày sinh
u s a phân s ph i khác 0
m s a sinh viên >=0 và <=10
…
thu c các nhóm trên (m i nhóm ít nh t
nguyên (A,B), sau ó
b Ki m tra xem t p A có ph i là con c a B hay không
Trang 11T.P.TU N - LTH T 41
9/6/2009
4 Các ph c ph ng th ng th c/hàm c bi t
T.P.TU N - LTH T 42
9/6/2009
c g i t ng, ng i dùng không c g i l i không tr i k t qu
Có hình th c tên trùng v i tên l p
ng
Có th khai báo trùng
4 Các ph c ph ng th ng th c/hàm c bi t
Constructor
T.P.TU N - LTH T 43
Date.h:
class Date
{
public:
Date();
Date(int, int, int);
int getYear();
int getMonth();
int getDay();
bool set(int, int, int);
void set(const Date&);
void print();
void copyTo(Date&);
bool equalTo(const Date&);
private:
int y, m, d;
};
Constructor
T.P.TU N - LTH T 44
date.cpp:
#include ”date.h”;
Date::Date() {
y = 2000;
m = 1;
d = 1;
}
Date::Date(int yy, int mm, int dd) {
set(yy, mm, dd);
}
Constructor
Trang 12T.P.TU N - LTH T 45
9/6/2009
myCalendar.cpp:
#include ”date.h”;
void main()
{
Date d1;
Date womenDay(2007, 3, 8) ;
Date d[100];
d1.print();
womenDay.print();
}
Constructor
T.P.TU N - LTH T 46
9/6/2009
Dùng nh ngh a và a kh i t o i t ng cùng 1 lúc.
Có tên trùng v i tên l p, không có ki u tr Không g i tr c ti p, s c t ng g i khi kh i t o t.
Gán giá tr , c p vùng nh cho các d li u thành viên nh viên.
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 báo nào là sai ? Point pt2;
Point pt3();
Point pt4 = Point(5,5);
Point pt5 = new Point(5,5);
……….
}
class Point {
int xVal, yVal;
public :
Point () // Hàm xây d ng m c nhiên
{ 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 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); … }
m o n
Không c n
ph i nh
i hàm EmptySet() khi kh i t o
nh
nh ngh a trùng
gi i phóng b nh ng óng t p
4 Các ph c ph ng th ng th c/hàm c bi t
Destructor
Trang 13T.P.TU N - LTH T 49
9/6/2009
Date.h:
class Date
{
public:
Date();
Date(int, int, int);
int getYear();
int getMonth();
int getDay();
bool set(int, int, int);
~Date();
private:
int y, m, d;
};
Destructor
T.P.TU N - LTH T 50
9/6/2009
date.cpp:
#include ”date.h”;
Date::Date() {
y = 2000;
m = 1;
d = 1;
}
Date::~Date()
{
cerr << y << m << d <<” bye!” << endl;
}
Destructor
T.P.TU N - LTH T 51
myCalendar.cpp:
#include ”date.h”;
void f1()
{
Date d(2007, 1, 1);
}
void main()
{
Date d;
f1();
}
Destructor
T.P.TU N - LTH T 52
n d p 1 i t ng tr c khi nó c khi c thu h i.
Cú pháp: ~TenLop() { …… } Không g i tr c ti p, s c t ng g i khi h y b t.
Thu h i vùng nh cho các d li u thành viên nh viên là con tr con tr
class Set 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);
}
ng c ng
có bao nhiêu
l n hàm h y
c g i ?
Trang 14T.P.TU N - LTH T 53
9/6/2009
class IntSet IntSet {
public:
//
private:
int elems[maxCard];
int card;
};
class RealSet RealSet {
public:
//
private:
float elems[maxCard];
int card;
};
p Các
Nguyên
p Các
Th c
void IntSet:: SetToReal (RealSet &set) { set.card = card;
for (register i = 0; i < card; ++i) set.elems[i] = (float) elems[i];
}
Hàm SetToReal dùng chuy n
p s nguyên thành t p s th c
Làm th nào
th c hi n c
vi c truy xu t
n thành viên Private ?
T.P.TU N - LTH T 54
9/6/2009
IntSet là b n ( n friend) c a l p friend RealSet
class IntSet IntSet { public:
//
private:
int elems[maxCard];
int card;
};
class RealSet RealSet { public:
//
friend void IntSet:: SetToReal SetToReal (RealSet&); private:
float elems[maxCard];
int card;
};
Gi nguyên nh ngh a c a l p IntSet
Thêm dòng khai báo
Friend cho hàm thành viên SetToReal
Cách 2:
Chuy n hàm SetToReal ra ngoài ( c l p) p
Khai báo hàm ó là b n a c 2 l p.
class IntSet IntSet {
public:
//
friend void SetToReal (IntSet &, RealSet&);
private:
int elems[maxCard];
int card;
};
class RealSet RealSet {
public:
//
friend void SetToReal (IntSet &, RealSet&);
private:
float elems[maxCard];
int card;
};
void SetToReal SetToReal (IntSet& iSet,
RealSet& rSet ) {
rSet.card = iSet.card;
for (int i = 0; i < iSet.card; ++i) rSet.elems[i] =
(float) iSet.elems[i];
}
Hàm c l p
là b n(friend)
a c 2 l p.
Hàm b n: n
Có quy n truy xu t n t t c các d li u và u hàm m thành viên (protected + private) c a 1 l p.
L p b n :
t c các hàm trong l p b n: là hàm b n.
class A;
class B { // ……….
friend class A;
};
class IntSet IntSet { ……… } class RealSet RealSet { // ……….
friend class IntSet;
};
Trang 15T.P.TU N - LTH T 57
9/6/2009
class CDate
{
friend CStudent; // friend class
private:
int d,m,y;
public:
friend void HoanVi(CDate &a,CDate &b);
//friend function
};
CStudent is a class
T.P.TU N - LTH T 58
9/6/2009
class CStudent {
private:
int id;
CDate ns;
public:
void setns(int d,int m,int y) {
ns.d=d; ns.m=m; ns.y=y;
} };
void HoanVi(CDate &a,CDate &b) {
int tam;
tam=a.d;a.d=b.d;b.d=tam; tam=a.m;a.m=b.m;b.m=tam; tam=a.y;a.y=b.y;b.y=tam; }
T.P.TU N - LTH T 59