LẬP TRÌNH C/C++ NÂNG CAO
Yêu cầu trước khi đọc: học xong Lập trình C/C++ căn bản
BÀI 3: NHẮC LẠI VỀ LỚP
Cơ bản về lớp
CODE
class Date{
int day;
public:
Date(int,int a=1);
int month;
void setDay(int);
void output();
};
int main(){
Date d(6);
d.month=3;
d.setDate(25);
d.output();
return 0;
}
Date::Date(int day,int month){
this->day=day;
this->month=month;
}
void Date::setDay(int day){
this->day=day;
}
void Date::output(){
cout<<day<<"/"<<month;
}
int main(){
Student s1;s1.id=2;
Student s2;s2.id=3;
cout<<equal(s1,s2);
}
bool equal(const Student& s1,const Student& s2){
return (s1.id==s2.id);
}
Overload toán tử (operator overload)
Ví dụ dưới sẽ overload toán tử ==
CODE
class Student{
public:
int id;
friend bool operator==(const Student&,const Student&);
};
int main(){
Student s1;s1.id=2;
Student s2;s2.id=3;
cout<<((s1==s2)?"equal":"unequal");
}
bool operator==(const Student& s1,const Student& s2){
return (s1.id==s2.id);
}
Overload toán tử nhập và xuất (input >> và output <<)
Mọi người đều biết cin>>a là gọi toán tử nhập cin.operator>>(a) hoặc
operator>>(cin,a) Overload 2 toán tử nhập và xuất này hết
sức quan trọng về sau. Nhân tiện mỗi khi cấp phát bộ nhớ, dùng xong phải
luôn hủy đi để thu hồi lại bộ nhớ đã cấp phát. Vì về sau
game cái ưu tiên hàng đầu là bộ nhớ, đừng để lại rác.
~myclass();
};
int main(){
myclass m;
return 0;
}
myclass::myclass(){
p=new int; //phải cấp phát bộ nhớ để tránh segmentation fault
}
myclass::~myclass(){
delete p;
}
Hàm khởi tạo sao chép (copy constructor
CODE
class Date{
public:
int day;int month;char *special;
Date(int,int,char*);
Date(const Date&);
~Date(){
delete [] special; //bởi vì chúng ta cấp phát bộ nhớ cho nó
}
};
Date::Date(int day,int month,char *special){
this->day=day;this->month=month;this->special=special;
}
Date::Date(const Date& d){
this->day=d.day;this->month=d.month;
this->special=new char[strlen(d.special)+1]; //cấp phát bộ nhớ cho nó
strcpy(this->special,d.special); //phải dùng strcpy với char array