3. Class Templates (Class Templates ( 類別樣板類別樣板 ))
Standard Template Library(STL)Standard Template Library(STL)
It is not completely compatible in C++ ComIt is not completely compatible in C++ Com
pilerpiler
Template prototypes and definitions shoulTemplate prototypes and definitions shoul
d locate at the same file(*.h), except usingd locate at the same file(*.h), except using
"export" if compiler support it"export" if compiler support it
4. Using template classUsing template class
Stack<int> kernels; // create a stack of intStack<int> kernels; // create a stack of int
Stack<String> colonels; // a stack of String objectsStack<String> colonels; // a stack of String objects
Template<class T>Template<class T>
void simple(T t) { cout << t << "n"; }void simple(T t) { cout << t << "n"; }
simple(2); // generate void simple(int)simple(2); // generate void simple(int)
simple("two"); // generate void simple(char *)simple("two"); // generate void simple(char *)
ExampleExample
stackitemstackitem
5. Stack pointer-incorrect versionStack pointer-incorrect version
Stack<String> s; // original stackStack<String> s; // original stack
Stack<char *> st; // alternate stackStack<char *> st; // alternate stack
String po;String po;
Three described version for "String po;"Three described version for "String po;"
1.1. char *po; // cin >> po; errorchar *po; // cin >> po; error
2.2. char po[40];char po[40];
// template <class Type>// template <class Type>
// bool Stack<Type>::pop(Type &item)// bool Stack<Type>::pop(Type &item)
// { ...; item = items[--top]; ... }// { ...; item = items[--top]; ... }
// item is Lvalue, cannot be array name// item is Lvalue, cannot be array name
3.3. char *po = new char[40];char *po = new char[40];
// push to the same address, and pop the same address value// push to the same address, and pop the same address value
// pop outcome is always the last push data// pop outcome is always the last push data
7. Template arrayTemplate array
Template is usually used in container classTemplate is usually used in container class
ArrayTP<ArrayTP<int,5>, 10> twodee;ArrayTP<ArrayTP<int,5>, 10> twodee;
int twodee[10][5];int twodee[10][5];
ExampleExample
arraytparraytp
8. Class Templates (Class Templates ( 類別樣板類別樣板 ))
template <class T> // Ttemplate <class T> // T 是樣板參數是樣板參數
class TStackclass TStack
{{
public:public:
TStack(int = 10) ;TStack(int = 10) ;
~TStack() { delete [] stackPtr ; }~TStack() { delete [] stackPtr ; }
bool Push(const T&);bool Push(const T&);
bool Pop(T&) ; // pop an element off the stackbool Pop(T&) ; // pop an element off the stack
bool isEmpty()const { return top == -1 ; }bool isEmpty()const { return top == -1 ; }
bool isFull() const { return top == size - 1 ; }bool isFull() const { return top == size - 1 ; }
private:private:
int size ; // Number of elements on Stackint size ; // Number of elements on Stack
int top ;int top ;
T* stackPtr ;T* stackPtr ;
};};
11. ContainmentContainment
Containment (composition, layering) is a hContainment (composition, layering) is a h
as-a relationshipas-a relationship
class Studentclass Student
{{
private:private:
String name; // use a String object for namString name; // use a String object for nam
ee
ArrayDb scores; // use an ArrayDb object fArrayDb scores; // use an ArrayDb object f
or scoresor scores
};};
13. Containment or private inheritanceContainment or private inheritance
Has-a relationship is generated fromHas-a relationship is generated from
containment and private inheritancecontainment and private inheritance
In general, we can use containment toIn general, we can use containment to
build up "has-a" relationshipbuild up "has-a" relationship
Private inheritance involved in somePrivate inheritance involved in some
particular status, such as accessingparticular status, such as accessing
protected member, or redefined virtualprotected member, or redefined virtual
functionfunction
20. Using virtual base classUsing virtual base class
If class indirectly inherit from a virtual baseIf class indirectly inherit from a virtual base
class, the constructor in base class shouldclass, the constructor in base class should
be involved except taking implicit default cbe involved except taking implicit default c
onstructoronstructor
-SingingWaiter(const Worker &wk, int p=0, int-SingingWaiter(const Worker &wk, int p=0, int
v=Singer::other): Waiter(wk,p), Singer(wk,v=Singer::other): Waiter(wk,p), Singer(wk,
v){} // flawedv){} // flawed
-SingingWaiter(const Worker &wk, int p=0, int-SingingWaiter(const Worker &wk, int p=0, int
v=Singer::other):v=Singer::other): Worker(wk)Worker(wk),Waiter(wk,p),,Waiter(wk,p),
Singer(wk,v){} // OKSinger(wk,v){} // OK
21. Array class (Array class ( 模擬語言內建的陣列模擬語言內建的陣列 ))
有次序性的容器,容納單一型別的多個元素有次序性的容器,容納單一型別的多個元素
。。
索引動作索引動作 (indexing)(indexing)
下標下標 (subscript [])(subscript []) 運算子運算子
22. Array class (Array class ( 模擬語言內建的陣列模擬語言內建的陣列 ))
Object-Based DesignObject-Based Design
Object_BasedObject_Based
Object-Oriented DesignObject-Oriented Design
Object-OrientedObject-Oriented
Generic DesignGeneric Design
Without Inheritance: GenericWithout Inheritance: Generic
With Inheritance: Generic_InheritanceWith Inheritance: Generic_Inheritance
標準的標準的 ArrayArray 其實是個其實是個 VectorVector
Vector_DemoVector_Demo
24. Container Classes and IteratorsContainer Classes and Iterators
Container classes (collection classes)Container classes (collection classes)
Classes designed to hold collections of objectsClasses designed to hold collections of objects
Provide services such as insertion, deletion, sProvide services such as insertion, deletion, s
earching, sorting, or testing an itemearching, sorting, or testing an item
Examples:Examples:
Arrays, stacks, queues, trees and linked listsArrays, stacks, queues, trees and linked lists
Iterator objects (iterators)Iterator objects (iterators)
Object that returns the next item of a collectionObject that returns the next item of a collection
(or performs some action on the next item)(or performs some action on the next item)
Can have several iterators per containerCan have several iterators per container
Book with multiple bookmarksBook with multiple bookmarks
32. ReferencesReferences
C++ How to Program 3rd.C++ How to Program 3rd.
STLSTL 源碼剖析源碼剖析
STLSTL中文站中文站
C++ Primer 3rdC++ Primer 3rd
C++C++ 教學範本教學範本
物件導向程式設計物件導向程式設計 hh
ttp://vr.me.ncku.edu.tw/courses/index-oop.htmttp://vr.me.ncku.edu.tw/courses/index-oop.htm