intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

LẬP TRÌNH C nâng cao - bài 3 - nhắc lại về lớp part 2

Chia sẻ: Yukogaru | Ngày: | Loại File: PDF | Số trang:6

104
lượt xem
20
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

BÀI 3: NHẮC LẠI VỀ LỚP Cơ bản về lớp Chúng ta sẽ được nhắc lại cách viết các hàm cơ bản để khởi tạo lớp và các hàm cơ bản liên quan.

Chủ đề:
Lưu

Nội dung Text: LẬP TRÌNH C nâng cao - bài 3 - nhắc lại về lớp part 2

  1. 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
  2. } Hàm khởi tạo Chúng ta có thể viết một hàm khởi tạo như thế này CODE class Student { string name;int age; public: Student(string name,int n):name(name),age(n) { } }; Nó tương đương với CODE class Student { string name;int age; public: Student(string name,int n) { (*this).name = name; this->age = n; } }; Hàm bạn (friend function) CODE class Student{ public: int id; friend bool equal(const Student&,const Student&); };
  3. int main(){ Student s1;s1.id=2; Student s2;s2.id=3; cout(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. CODE class Date{
  4. public: int day;int month; friend istream& operator>>(istream&,Date&); friend ostream& operator(istream& ins,Date& d){ ins>>d.day; ins>>d.month; ins.get(); //phải xóa bộ đệm return ins; } ostream& operator
  5. 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 } int main(){
  6. Date d1(29,8,"birthday"); Date d2(d1); cout
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2