# C++筆記 Defining Class ###### tags: `C++` 為了實踐物件導向,Class(物件)為不可少的元素之一,物件定義了該物件所具有的特質(property)與能力(capacity)。 --- ## Data Abstraction 人遇到複雜問題的時候,會藉由將問題抽象化來幫助解決問題。 _例如:面對一個圖書館借書系統,可能會引進管理人員和借還書系統抑或是書籍, 論文和雜誌等等物件。利用這些物件彼此的互動關係來達到圖書館的完整系統。_ 故解決問題時,第一個該做是 _分析_ ,分析出在這個問題下,物件與物件之間的關係與他們該具備哪些特質與能力。在C++中,物件包含了data members 和 member funuctions,其中data member表示該物件所具備的特質,而member functions表示了該物件所具備的能力。 ## Data Encapsulation 當在定義一個物件的時候,會定義私有成員(private member)代表無法從外部直接存取該成員和公開成員(public member)代表外部可以直接存取該成員。若外部想存取私有成員必須藉由公開方法(public function)來取得或修改該私有成員,這樣做的目的是為了保護私有成員的存取是安全的。 ```cpp= // account.h #ifndef _ACCOUNT_ #define _ACCONUT_ #include <iostream> #include <string> using namespace std; class Account{ private : string name; unsigned long nr; double balance; public : bool init(const string& name, unsigned long nr, double balance); void display(); } #endif ``` 上例中, private, public的修飾詞就是用來表示接下來的成員屬於該種成員,若都沒有寫private, public,在Class中預設為private成員。 ```cpp= // Account.cpp // define methods #include "account.h" #include <iostream> #include <string> using namespace std; bool Account::init( const string& in_name, unsigned long in_nr, double in_balance){ if(in_name.size() < 1){ return false; // no empty name } name = in_name; nr = in_nr; balance = in_balance; return true; } void Account::display(){ cout << fixed << setprecision(2) << "Name : ", name << "\n" << "Number : ", nr << "\n" << "Balance : ", balance << "\n" << "-------------------------\n" << endl; } ``` --- ### Class Member Access Operator 1. 物件使用 . 符號來存取 ```cpp= Account current; current.init("Chou", 1125, 6000); //initialize current.name = "Chang"; // error. 因為name為private, 無法從外部存取. ``` 2. 指標使用 -> 符號來存取 ```cpp= Account current; Account* ptrAccount = &current; ptrAccounut->init("Chou", 1125, 6000); // 等同於(*ptrAccount).init("Chou", 1125, 6000) ``` #### Strcut & Class Struct 與 Class的差別僅在於Data encapsulation上, struct若無定義成員為私有或是公開時, 預設值為Public, 而Class的預設為Private. --- ## Union 一般來說,一個物件中的成員都有著自己的記憶體空間,但是在union底下,所有的成員是共享一個記憶體區塊的,union沒辦法一次同時儲存多個資料,但相對的,union在記憶體上的操作變得更多樣性。 ```cpp= // WordByte.h #include <iostream> using namespace std; union WordByte{ private: unsigned short w; unsigned char c[2]; public: unsigned shor& word(){return w;} unsigned char& lowByte(){return c[0];} unsigned char& highByte(){return c[1];} } int main(){ WordBtye w; w.word() = 256; cout << "Word : " << (int)w.word() << endl; // 256 cout << "Low-Byte: " << (int)w.lowByte() << endl; // 0 cout << "High-Byte: " << (int)w.highByte() << endl; // 1 return 0; } ``` 上面的例子,因為unsigned short w, unsigned char c[2]他們共用的是相同的記憶體區塊, unsigned short為16bit, unsigned char 為8bits. 故c[0]為w的前8bit, c[1]為w的後8bit. --- ### Reference <a href="http://www.lmpt.univ-tours.fr/~volkov/C++.pdf">C++ from scratch</a>