[重修] 計算機程式-9 & 10 Classes and data abstraction I, II
class就是一個"模板" 有了模板就可以創造出 有同樣屬性特徵(data)跟行為方法(member function)的物件.
那為什麼要學物件導向呢. 這裡有個影片解釋的還不錯, 好處呢不外乎就是 更容易維護, 更用人的角度來設計程式. 當一個程式大的時候 有物件的觀念會讓事情簡單不少. 至於怎麼設計, 怎樣應對 interview 推薦經典書,
- Design Patterns - Elements of Reusable Object-Oriented Software
整理以下重點,
1) 如果物件是個pointer 要使用裡面的東西就要用"->"
count counter;
count *counterPtr = &counter;
count &counterRef = counter;
counter.x = a;
counterRef.x = a;
counterPtr -> x = a
2) 系統自動會建立 default的建構子, 當然我們也可以overloading
3) 好的寫法是分成3個檔案. time.h, time.cpp, main.cpp
- time.h 定義 class
- time.cpp 定義 class 行為方法實作
- main include time.h
重複的include .h file 我們可以用 #ifndef 做判斷來避免
4) const member function 宣告的方式有些特別,
int Time:getHour() const{
return hour;
}
5) 物件是可以被複製的
Time t1 = t2;
6) friend function
A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.friend function: 簡單來說就是你在class裡面定義了一個friend function,這個function是在class的外面,同時這個function可以修改private data。
7) this pointer
最大的好處是可以用來做串接.
比如 t.setm(1).seth(2).setd(3);
8) static member function
We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member.
留言
張貼留言