c++ OOP
使用c++演示基本OOP
- 為什麼需要?
我們希望機器能讀懂要做什麼,將程式碼編寫成人類行爲方便閱讀
- 其中最主要的就是纇(Class)這個物件,而在類中,定義類型為最重要的一件事
- 在類中有3個修飾符,分別是private,protected和public,默認為private
- private外界無法訪問(黑色地帶)
- protected介於private和public中間,繼承時用到(灰色地帶)
- product外界可以訪問(白色地帶)
- 如果我們今天有100筆資料,修改繁雜且緩慢
- 使用構造函數(Constructors)解決
- 沒有函數返回值,包括void類型定義
- 函數名稱和類名稱相同
- 請將Constructors放在public,他可以放在其他地方但很麻煩
- 封裝
- 抽象
- 繼承
- 多態性
- 不希望其他的類可以直接對纇進行操作,將值放入private
- 封裝中主要使用setter和geter方法對值進行操作
- 當你有像很複雜的產品不希望被人知道他複雜的地方
- 所有繼承了抽象的類都必須實現抽象的方法(虛函數)
- 我們有沒有辦法不要透過getName()來獲得父類別的元素
- 沒有辦法獲得父類別的所有屬性,包括抽象函數
- 直接使用父類別完成子類別的各種方法
- 遇到還是使用父類別的方法時,可以使用虛擬函數來解決
- 為什麼虛擬函數可以解決?
- 虛擬函數會去檢查最底層的繼承者有沒有使用虛擬函數,如果有的話就使用
- 當我需要可以使用其他類別的private時,直接引入發現因為private而不可訪問
- 多載運算子的名稱是 operatorx,其中x是下表中顯示的運算子。例如,若要多載加運算子,您可以定義稱為 operator+的函式。
- 為什麼要運算子多載?
- 當成員元素為private時,只要一多就會需要大量get和set相加,使用運算子多載可以避免這種狀況
- 如何決定運算子參數數量?
- 使用運算子多載以外需要運算的類別
- static能夠讓指定變數跳脫做用域
- extern可以讓變數再不同文件傳輸,宣告了extern的變數等同於在這個文件裡面有一個變數可以用,但是這個變數的宣告並不在此,而是有某個 include 了 此文件的人會去做宣告