首页 > 其他 > 详细

条款41: 区分继承和模板

时间:2014-08-24 14:05:52      阅读:328      评论:0      收藏:0      [点我收藏+]

· 当对象的类型不影响类中函数的行为时,就要使用模板来生成这样一组类。
· 当对象的类型影响类中函数的行为时,就要使用继承来得到这样一组类。

下面的代码通过定义一个链表来实现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;
}

 

条款41: 区分继承和模板

原文:http://www.cnblogs.com/ljygoodgoodstudydaydayup/p/3932706.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!