1. Trang chủ
  2. » Công Nghệ Thông Tin

Bài giảng: Lập trình hướng đối tượng pdf

80 325 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 80
Dung lượng 736,3 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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 1

 Các khái nim c s

Trang 3

i tng phn m m i tng phn m mSinh Vi ên

bi giá tr c th gi là

thu c 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 6

 Thu c tính (attribute) là d liu trình bày các

Trang 7

Tru 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 9

Tính K Tha (Inheritance)

Trang 11

Hàmthành viên

[ <Quy n truy xut> LPCHA ] PCHA

{ <Quy n 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 13

 Tê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 14

void 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 17

 Thu 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 19

Hà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 20

Array(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 &copy) : 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 21

Array(int size) : size(size), data(new int[size]) {}

~Array() { delete data; }

Array(const Array &copy)

: 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 22

cout<<"Nhap x"; cin>>p.xVal;

cout<<"Nhap y"; cin>>p.yVal;

} void main(){

Point p1,p2;

p1.InputPoint(p2);

}

Trang 23

cout<<"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 24

void 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 truy n 1 tham s, 1 pth c truy n 2 tham s)

 To mt phng th c sao chép constructor

Trang 25

int 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 26

vic 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 27

class IntSet IntSet{ ……… }

class RealSet RealSet{ // ………

friend class IntSet;

};

Trang 28

Khai báo

Khi tod liuthành viênt!nh

<<st.getNextID();}

Trang 29

i s thành viên n

 Con tr ! *this: *this

 Là 1 thành viên ∗n, có thuc tính là private.

Trang 30

Thành viên tham chi u

 Tham chiu d liu thành viên:

dng mc nhiên - default constructor).

Trang 31

 D 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 34

Person::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 37

protected

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 38

Hàmc ngtên



Chuyn kiu

 i tng lp cha = i tng lp con;

OptionList data members Window data members Menu data members

Trang 39

Liê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 40

Liê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 43

Tá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 44

Tá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 45

friend 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 46

Point (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 48

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

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 49

Point (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 50

Matrix& 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 ++ &

 Ti n 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 51

class 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 53

cout<<“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 54

class 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 55

cout << “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 56

cout << “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 59

cout<<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 63

while ( 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

 Thu c tính (attribute) d liu trình bày các

Trang 7

Ngày đăng: 28/07/2014, 14:21

TỪ KHÓA LIÊN QUAN