C++的面向對象內容還是很多的,內容繁雜,體系龐大,想起家里的Prime的厚度,心里一小顫。二級考試教材只涉及了C++最基礎的語(yǔ)法,比如類(lèi)之間的繼承關(guān)系,虛函數等,至于泛型編程基本沒(méi)有涉及?,F在自己感覺(jué)不熟的就是C++的三個(gè)部分:泛型編程、面向對象設計和運算符重載。今天重新看了下這部分,把感覺(jué)重要的來(lái)寫(xiě)一寫(xiě)。
1. 構造函數中的初始化有兩種方式,一種是針對參數的直接設置默認值,如(constructor(int num = 1, int sum = 0)),另一種則是在函數原型之后附加上初始化列表,針對參數、成員數據進(jìn)行初始化,值得一提的是,對于const/static成員、沒(méi)有默認構造函數的類(lèi)對象成員都需要使用第二種方式進(jìn)行初始化。
2. Mutalbe和Const。有些時(shí)候我們希望變量在程序運行過(guò)程中保持不變,會(huì )為其設置const屬性;但是此時(shí)如果傳入參數的過(guò)程修改參數的數據就會(huì )引發(fā)錯誤,因此我們可以將函數過(guò)程也聲明為const(常函數),如(int length() const {return _length;}),編譯器就會(huì )檢查常函數是否修改了類(lèi)對象的數值。但是還有些時(shí)候我們認為類(lèi)對象中的某些屬性與對象核心屬性無(wú)關(guān),可以改變,就將其聲明為mutable類(lèi)型,則const函數也可以改變其值。應該說(shuō)C++的const/mutalbe提供了非常大的靈活性。更詳細和深入的內容留待以后實(shí)際用到時(shí)才補充。
3. Static成員。對于類(lèi)中的static成員屬于類(lèi)中所有對象所共有的,因此每個(gè)類(lèi)中只有一份,沒(méi)有副本。靜態(tài)成員函數的主要目的是使得與類(lèi)成員數據無(wú)關(guān)的操作函數可以獨立于類(lèi)對象而直接調用,如class::function而非object.function。
最后,學(xué)習編程不敲代碼果然不行,哪怕比著(zhù)書(shū)上的例子敲呢!這里附上一個(gè)關(guān)于棧的類(lèi),可以看到關(guān)于類(lèi)的基本的語(yǔ)法點(diǎn)。
- #include <cstdlib>
- #include <iostream>
- #include <vector>
- #include <string>
-
- using namespace std;
-
- //Class Stack Define
-
- class Stack
- {
- //類(lèi)中聲明成員函數,可以給出簡(jiǎn)單函數的定義,默認作為inline使用,如這里的size()
- public:
- bool push( string &);
- bool pop(string &elem);
- bool peek(string &elem);
- bool empty();
- bool full();
-
- int size() {return _stack.size();}
- private:
- vector<string> _stack;
- };
- //Initial Stack
- //EOF is ctrl + D
- //本例充分使用了vector的泛型算法
- void fill_stack(Stack &stack, istream &is = cin)
- {
- string str;
- while (is >> str && !stack.full())
- stack.push(str);
- cout << "Read in "<< stack.size()<< " elements\n";
- }
-
- bool Stack::push(string &elem)
- {
- if (full())
- return false;
- _stack.push_back(elem);
- return true;
- }
-
- inline bool
- Stack::empty()
- {
- return _stack.empty();
- }
-
- bool
- Stack::pop(string &elem)
- {
- if (empty())
- return false;
- elem = _stack.back();
- _stack.pop_back();
- return true;
- }
-
- inline bool
- Stack::full()
- {
- return _stack.size() == _stack.max_size();
- }
-
- //peek() is used to check the last elem in Stack
- bool Stack::peek(string &elem)
- {
- if (empty())
- return false;
- elem = _stack.back();
- return true;
- }
-
-
-
- int main(int argc, char *argv[])
- {
- cout <<"A Stack Test...\n";
-
- string elem;
- string &r_elem = elem;
-
- Stack stack;
- fill_stack(stack);
- stack.peek(r_elem);
- cout << "the last elem is : "<< r_elem<<endl;
-
- system("PAUSE");
- return EXIT_SUCCESS;
- }
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。