Point Int xVal, yVal; setPointint x, int y; MovePtint x, int y TÊN LP D liuthành viên Hàmthành viên void SetPt int, int; void Move int, int; i tng To ra i tngthuc lpPoint... void setPtin
Trang 1Các khái nim c s
Trang 3i tng phn mm i tng phn mmSinh Vi ên
bi giá tr c th gi là
thuc tính th hin
c gi là mt th hin
I TNG = THUC TÍNH + PHNG THC
C:8 Nguyn Vn Tráng
MSSV:1234
Tên: Tèo Gii tính:
Nam
Hc bài
KMH
Kim tra Ng
Trang 5
Khai báo cho lp
SinhVien
i tng ca lpSinhVien
C:8 Nguyn
V∃n Tráng
MSSV:1234
Tên: Tí Gii tính: Nam
MSSV:0000
Tên: Tèo Gii tính: Nam
KMH
Kim tra
Ng
C:8 Nguyn V∃n Tráng
MSSV:1234
Tên: Tí Gii tính: Nam
Trang 6Thuc tính (attribute) là d liu trình bày các
Trang 7Tru tng hoá (Abstraction)
n cách thc hin (HOW).
Trang 8
Tính Bao Gói (Encapsulation)
óng gói (encapsulation) là ti n trình che
n Thông Tin
(Information Hiding)
Vic che giu nhng chi
c gi làn thông tin
Trang 9Tính K Tha (Inheritance)
Trang 11Hàmthành viên
[ <Quyn truy xut> LPCHA ] PCHA
{ <Quyn truy xut>:
Trang 12
Point
Int xVal, yVal;
setPoint(int x, int y);
MovePt(int x, int y)
TÊN LP
D liuthành viên
Hàmthành viên
void SetPt (int, int);
void Move (int, int);
i tng
To ra
i tngthuc lpPoint
Trang 13Tên thành viên b che bi bi n cc b.
Ví d: Point(int xVal, int yVal) {
Point::xVal = xVal;
Point::yVal = yVal;
}
Trang 14void setPt(int x, int y);
void MovePt(int x, int y);
void Print(){
cout<< “(” << x << “,” << y<< “)” << endl;
}};
void Point::setPt(int x, int y){
Trang 15
class Rectangle Rectangle{ // Lp lng nhau
int x, y;
};
Point topLeft, botRight;
};
Rectangle::Point pt(1,1); // sd ngoài
void Render (Image &i)
Trang 16
Hàm khi to (Contructor)
Có tên trùng vi tên lp, không có kiu tr v
Point (float len, float angle) {
xVal = (int) (len * cos(angle));
yVal = (int) (len * sin(angle));
Trang 17Thu h i vùng nh cho các d li thành viên là viên con tr .
class Set Set {
Set(const int size) { …… }
~Set() { delete elems; }
…
};
void TestFunct1(Set s1) {Set *s = new Set(50);
}
void main(){Set s1(40), s2(50);
TestFunct1(s1);
}
T,ng cng
cóbaonhiêulnhàm hy
c gi ?
class Point Point{
int xVal, yVal;
Point (int x = 0, int y = 0);
Point (float x=0, float y=0);
Trang 19Hàm khi to sao chép
#include <iostream>
class Person {
public: int age;
Person(int age) : age(age) {}
};
void main() {
Person timmy(10);
Person sally(15);
Person timmy_clone = timmy;
cout << timmy.age << " " << sally.age << " " << timmy_clone.age << endl;
public: int age;
Person(int age) : age(age) {}
Person(Person const& copy) : age(copy.age) {}
};
void main() {
Person timmy(10);
Person sally(15);
Person timmy_clone = timmy;
cout << timmy.age << " " << sally.age << " " << timmy_clone.age << endl;
timmy.age = 23;
cout << timmy.age << " " << sally.age << " " << timmy_clone.age << endl;
}
Trang 20Array(int size) : size(size), data(new int[size]) {}
~Array() { delete data; }
};
int main() {
Array first(20);
first.data[0] = 25;
Array copy = first;
cout << first.data[0] << " " << copy.data[0] << endl;
Array(int size) : size(size), data(new int[size]) {}
~Array() { delete data; }
Array(const Array ©) : size(copy.size), data(copy.data) {}
Array copy = first;
cout << first.data[0] << " " << copy.data[0] << endl;
first.data[0] = 10;
cout << first.data[0] << " " << copy.data[0] << endl;
}
Trang 21Array(int size) : size(size), data(new int[size]) {}
~Array() { delete data; }
Array(const Array ©)
: size(copy.size), data(new int[copy.size]) { memcpy((void*)data, copy.data, sizeof(copy.data));
Array copy = first;
cout << first.data[0] << " " << copy.data[0] << endl;
Trang 22cout<<"Nhap x"; cin>>p.xVal;
cout<<"Nhap y"; cin>>p.yVal;
} void main(){
Point p1,p2;
p1.InputPoint(p2);
}
Trang 23cout<<"Nhap x"; cin>>p.xVal;
cout<<"Nhap y"; cin>>p.yVal;
} void main(){
const int int width;
const int int height;
class Image Image{
const int width = 256;
const int height = 168;
Trang 24void PrintPt() const;
void SetPt(int x, int y){
const Point p(10,13);
p.SetPt(10,14); // SAI p.PrintPt(); // úng
}
Bài tp
hp này có th thc hin các ch c n∃ng sau:
pth c truyn 1 tham s, 1 pth c truyn 2 tham s)
To mt phng th c sao chép constructor
Trang 25int IsMember(const int);
void AddElem(const int);
void RmvElem(const int);
void Copy(IntSet&);
int Equal(IntSet&);
void Interset(IntSet&, IntSet&);
void Union(IntSet&, IntSet&);
max = size; num=0;
elems = new int[size];
}IntSet::IntSet(){
elems = new int[100];
num = 100;
}int IntSet::IsMember(const int e){
for(int i=0; i<num; i++)if(elems[i]==e)
private: int *elems;
int num, max;
public:
RealSet();
RealSet(int);
void EmptySet(){num =0;}
int IsMember(const float);
void AddElem(const float);
void RmvElem(const float);
void Copy(RealSet&);
int Equal(RealSet&);
void Interset(RealSet&, RealSet&);
void Union(RealSet&, RealSet&);
num = 100;
elems = new float[100];
}int RealSet::IsMember(const float e){
for(int i=0; i<num; i++)if(elems[i]==e)
return 1;
return 0;
}
……
Trang 26vic truy xut
n thành viên
Private ?
Hàm bn (Friend)
Cách 1: Khai báo hàm thành viên ca lp IntSet là
class IntSet IntSet{public:
ngh!a ca lp IntSet
Thêm dòng khai báo
Friendcho
hàm thành viên
SetToReal
Trang 27class IntSet IntSet{ ……… }
class RealSet RealSet{ // ………
friend class IntSet;
};
Trang 28Khai báo
Khi tod liuthành viênt!nh
<<st.getNextID();}
Trang 29i s thành viên n
Con tr ! *this: *this
Là 1 thành viên ∗n, có thuc tính là private.
Trang 30Thành viên tham chi u
Tham chiu d liu thành viên:
dng mc nhiên - default constructor).
Trang 31D liu thành viên có th có kiu:
D liu (lp) chu∗n ca ngôn ng.
Trang 32
Sa bài tp
Khi i t ng là tham s ca hàm l u ý Nên truyn
tham bin vì nu truyn tham tr s t ng sao
chép ra mt i t ng khác, nu trong class có
thuc tính là con tr và hàm destructor gii phóng
con tr mà không s dng hàm copy constructor s
gây ra li >do nó hu luôn i t ng truyn vào.
(INHERITANCE)
Trang 34Person::Person(Date d, char *n, char *p)
:date(d), name(n), place(p){}
void Person::Print(){
cout<<"Ho ten: "<<name<<endl;
cout<<"Ngay sinh: "; date.Print();
Trang 36
Có tt c các d liu và hàm thành viên.
Cho phép lp con truy xut.
// cac thanh vien chung
Trang 37protected
protectedprivate
public
public
_
private
Tha k protected Tha k private
Tha k public Lp c s∀
Window data members
Menu data members
class OptionList OptionList{public:
OptionList (int n);
~OptionList ();
//
};
Trang 38Hàmc ngtên
Chuyn kiu
i tng lp cha = i tng lp con;
OptionList data members Window data members Menu data members
Trang 39Liên k t tnh ( static binding ):
Liên k t tnh ( static binding ):
cout.fill('0'); cout.width(2); cout<<hrs<<":";
cout.fill('0'); cout.width(2); cout<<mins<<":";
cout.fill('0'); cout.width(2); cout<<secs<<endl;
cout.fill('0'); cout.width(2); cout<<hrs<<":";
cout.fill('0'); cout.width(2); cout<<mins<<":";
cout.fill('0'); cout.width(2); cout<<secs<<":"<<zone<<endl;
Trang 40Liên k t tnh ( static binding ):
void Print (Timer someTime ){
Liên k t ng ( dynamic binding )
Trang 41
Timer(int h, int m, int s):hrs(h), mins(m), secs(s){}
virtual void WriteTime(){
cout.fill('0'); cout.width(2); cout<<hrs<<":";
cout.fill('0'); cout.width(2); cout<<mins<<":";
cout.fill('0'); cout.width(2); cout<<secs<<endl;
cout.fill('0'); cout.width(2); cout<<hrs<<":";
cout.fill('0'); cout.width(2); cout<<mins<<":";
cout.fill('0'); cout.width(2); cout<<secs<<":"<<zone<<endl;
}
};
Liên k t ng ( dynamic binding )
void Print (Timer* someTime ){
Trang 42
class OptionList OptionList
: public Widget, List
{ /* */ };
class Window Window
: public Widget, Port
class OptionList OptionList
: virtual public Widget,
public List
{ /* */ };
class Window Window
: virtual public Widget,
Menu::Menu (int n, Rect &bounds) :
Widget(bounds), OptionList(n), Window(bounds)
{ // }
Ch& có 1
i tng Widget
Trang 43Tái nh ngha toán t (tt)
class Point 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); }
Trang 44Tái nh ngha toán t (tt)
B∋ng hàm c lp: thng khai báo friend
class Point 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:
Set(void) { num = 100; elems = new int[100];}
friend int operator & (const int, Set&);// thanh vien ?
friend int operator ==(Set&, Set&); // bang ?
friend int operator !=(Set&, Set&); // khong bang ?
friend Set operator * (Set&, Set&); // giao
friend Set operator + (Set&, Set&); // hop
//
void AddElem(const int elem);
void Copy (Set &set);
void Print (void);
if (20 &s1) cout << "20 thuoc s1\n";
cout << "s1 giao s2 = "; (s1 * s2).Print();
cout << "s1 hop s2 = "; (s1 +s2).Print();
if (s1 !=s2) cout << "s1 /= s2\n";
return 0;
}
Trang 45friend Point operator + (Point, Point);
friend Point operator + (int, Point);
friend Point operator + (Point, int);
Point (int x) { Point::x = Point::y = x; }
friend Point operator + (Point, Point);
Trang 46Point (int x) { Point::x = Point::y = x; }
friend Point operator + (Point, Point);
Point(int x, int y):xVal(x),yVal(y){}
Point(int x){Point::xVal = Point::yVal = x;} // constructor chuyn kiu
friend Point operator + (Point, Point);
};
Point operator + (Point p1, Point p2){
return Point(p1.xVal+p2.xVal, p1.yVal+p2.yVal);
Trang 47
Tái nh ngha toán t xut <<
ostream& operator << (ostream&, Class&);
class Point Point{
public:
Point (int x=0, int y=0)
{ Point::x = x; Point::y = y; }
friend ostream& operator <<
(ostream& os, Point& p)
Tái nh ngha toán t nhp >>
istream& operator >> (istream&, Class&);
class Point Point{
public:
Point (int x=0, int y=0)
{ Point::x = x; Point::y = y; }
friend istream& operator >>
(istream& is, Point& p)
Trang 48char **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() {
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 hàng
const short cols; // s ct
static double dummy = 0.0;
return (row >= 1 && row <= rows
&& col >= 1 && col <= cols)
Trang 49Point (int =0; int =0 );
// Khong can thiet DN
Point (const Point& p) {
int n = rows * cols;
elems = new double[n]; // cùng kích thcfor (register i = 0; i < n; ++i) // sao chép phn t%
elems[i] = m.elems[i];
}
Trang 50Matrix& operator = (const Matrix &m) {
if (rows == m.rows && cols == m.cols) { // phi khpint n = rows * cols;
for (int i = 0; i < n; ++i) // sao chép các phn t%
elems[i] = m.elems[i];
}return *this;
} };
Hàm
thành
viên
Tái nh ngha toán t ++ &
Tin t: ++n
H∋u t: n++
class PhanSo PhanSo{
int tuso, mau so;
public:
// …
PhanSo(int=0 , int =1);
friend PhanSo operator ++ (PhanSo&);
friend PhanSo operator ++ (PhanSo&, int);
};
PhanSo operator ++ (PhanSo& p) {
return (p = PhanSo(tuso+mauso, mauso));
}
PhanSo operator ++ (PhanSo& p, int x) {
PhanSo p2 = PhanSo(tuso+mauso, mauso);
Trang 51class Point 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;
}
Trang 53cout<<“Nhap tu so: ”; cin>>ts;
cout<<“Nhap mau so:”; cin>>ms;
cout<<“gia tri cua ps:”<<GiaTri(ts,ms);
}
L∀i chia cho 0
Gii pháp
class XLLOI{};
float GiaTri(int tu, int mau){
if(mau==0) throwXLLOI();
return (float)tu/mau;
}
void main(){
int ts,ms;
cout<<“Nhap tu so: ”; cin>>ts;
cout<<“Nhap mau so:”; cin>>ms;
Trang 54class A{ };
class B{ }
void SinhLoi(int a){
if(a>0) throwA();
if(a>0) throwA();
throwB();
}void main(){
class A{ };
class B{ }
void SinhLoi(int a){
if(a>0) throwA();
if(a>0) throwA();
throwB();
}void main(){
Trang 55cout << “Gia tri PS la: “ << gt;
} catch ( Loi_Chia_0 loi ) {
cout << “Loi chia “ << loi.ts <<
“ cho 0”;
} }
C ch b∀t l!i
throw
Trang 56cout << “Loi bi bat ln 1”;
throw ; // duy tri loi
}
}
void main() { try { BatLoi();
} catch ( Loi ) { cout << “Loi bi bat lan hai”;
} }
Trang 57
Dùng liên k t ng x lý l!i
// loi truy cap
if ( num <= 0 ) throw ( Loi_KT(num) );
elems = new int[num];
}
~Array() { delete elems; }
int phantu(int i){
if ( i<0 || i>=num ) throw ( Loi_TC(i) );
return elems[i];
}
};
Trang 59cout<<n;
nó hai toán hng, mt là “lung xut - output
stream”(cout), hai là biu th c mà ta mun xut
(n).
cin>>x
2 toán hng, mt là “lung nh∋p – input
stream”(cin), hai là bi n mà ta lu giá tr.
Khái nim lung?
g8n vi các thi t b vào ra.
phím, máy scan, file
hình, máy in, file
Trang 63while ( cin.get(c) ){ //ly các ký t t lung nhp vào c
cout.put(c); // a c vào lung xut
if(c==‘\n’) break;
}
ISTREAM
istream & getline(char * ch, int size, char delim=’\n’)
- khi gp ký t phân cách delim thì hàm ng8t
putback(char c) : tr li lung nh∋p 1 ký t
peek() : a ra ký t k ti ... 6
Thuc tính (attribute) d liu trình bày các
Trang 7