slide

Views:
 
Category: Entertainment
     
 

Presentation Description

thầy Long

Comments

Presentation Transcript

Kế thừa private : 

Kế thừa private class nguoi { // friend class sinhvien; protected: char *hoten; int namsinh; public: nguoi(char *ht,int ns):namsinh(ns){hoten=strdup(ht);} ~nguoi(){delete [] hoten;} void xuat ()const; friend ostream & operator <<(ostream &os,nguoi &p); int is20tuoi(); }; int nguoi::is20tuoi() { if(this->namsinh==1988)return 1; return 0; } void nguoi::xuat()const { cout<<"nguoi,hoten:"<<hoten<<" namsinh"<<namsinh<<"\n"; } ostream & operator <<(ostream &os,nguoi &p) { return os<<"hoten:"<<p.hoten<<"namsinh"<<p.namsinh<<"\n"; } class sinhvien : private nguoi //kế thừa private { char *maso; public: sinhvien(char *ht,int ns,char *ms):nguoi(ht,ns) { maso=strdup(ms); } ~sinhvien(){delete [] maso;} int is20tuoi(){return nguoi::is20tuoi();} void xuat(); }; void sinhvien::xuat() { cout<<"sinhvien,maso:"<<maso<<"hoten"<<hoten<<"\n"; //this->nguoi::hoten="helo"; } void main() { nguoi thai("vuongnhatthai",1990); sinhvien a("Nguyen Anh Tai",1988,"0611261"); a.xuat(); // a.nguoi::xuat(); cout<<thai; int kiemtra=a.is20tuoi(); } Ở đây lớp sinh viên truy xuất private của nguoi đc (ảnh 1).Tức là nó vẫn có cấu trúc dữ liệu của lớp cha Nếu có dòng này thì báo lỗi như bên dưới(ành 2).Nguyên nhân là public của người thì sinhvien ko có quyền truy xuất Tất nhiên phương thức thiết lập của lớp cha vẫn dùng được(ảnh 3) ảnh 2 anh1 ảnh 3 Chữ xanh:sử dụng lại thao tác của lớp cha. Dòng này để sửa lỗi ko truy xuất dc

Phép tóan >> : 

Phép tóan >> class vector { int dim; int *data; public: vector(int x) { if(!x)data=NULL; else { dim=x; data=new int[dim]; } } friend istream &operator >>(istream &is,vector &a); }; istream &operator >>(istream &is,vector &a) { cout<<"nhap vao toa do:"<<"\n"; for(int i=0;i<a.dim;i++) { is>>a.data[i]; } return is; } void main() { vector a(2); vector b(2); cin>>a>>b; } 2 cái dấu & nếu ko có sẽ sai vì nếu ko có:thì biến is chỉ là biến cục bộ nên sẽ sai ở câu lệnh cin>>a>>b;