条款41: 区分继承和模板
· 当对象的类型不影响类中函数的行为时,就要使用模板来生成这样一组类。
· 当对象的类型影响类中函数的行为时,就要使用继承来得到这样一组类。
下面的代码通过定义一个链表来实现Stack类,假设堆栈的对象类型为T:
template<class T> class stack { public: stack(); ~stack(); void push(const T&object); T pop(); bool empty()const; private: struct stackNode { T data; stackNode *next; stackNode(const T &newData, stackNode *nextNode) :data(newData), next(nextNode){} }; stackNode *top; stack(const stack &rhs);//防止拷贝和赋值 stack &operator=(const stack &rhs); }; template<class T> stack<T>::stack() :top(0){} template<class T> void stack<T>::push(const T &object) { top = new stackNode(object, top); } template<class T> T stack<T>::pop() { stackNode *temp = top; top = top->next; T data = temp->data; delete temp; return data; } template<class T> stack<T>::stack() { while (top) { stackNode *temp = top; top = top->next; delete temp; } } template<class T> bool stack<T>::empty()const { return top == 0; }