zoukankan      html  css  js  c++  java
  • 条款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;
    }
  • 相关阅读:
    DAY12 基本余数 运算符2
    DAY11 基本运算符
    DAY10 变量 常量 作用域
    DAY09 JAVA 类型转换
    DAY08 数据类型2
    DAY07 数据类型
    DAY06 JAVA基础语法1注释2标识符
    Beta冲刺集合
    Alpha冲刺集合
    高级软件工程实践总结
  • 原文地址:https://www.cnblogs.com/ljygoodgoodstudydaydayup/p/3932706.html
Copyright © 2011-2022 走看看