模板 template

2019-04-21  本文已影响0人  cb_guo

template

模板函数

#include<iostream>
using namespace std;

template<typename  T> 
void sw(T& t1, T& t2) {
    T tmpT;
    tmpT = t1;
    t1 = t2;
    t2 = tmpT;
}

int main(){
    int a = 1, b = 2;
    sw(a, b);
    cout<<a<<" "<<b<<endl;
}

模板类

#include<iostream>
using namespace std;

template<class T>
class Stack{
    public:
        Stack(){
            size = 0;
            maxsize = 10;
            array = new T[maxsize];
            cout<<"crete"<<endl;
        }

        ~Stack(){
            cout<<"xi gou"<<endl;
        }

        T top(){
            if(size > 0){
                return array[size];
            }
            else{
                cout<<"zhan kong"<<endl;
            }
        }

        void pop(){
            if(size > 0){
                size--;
            }
            else{
                cout<<"zhan kong"<<endl;
            }
        }

        void push(T temp){
            size ++;
            array[size] = temp;
        }

    private:
        int size;
        int maxsize;
        T*  array;
};


int main(){
    // Stack<int> sk;
    // sk.push(1);
    // sk.push(2);
    // sk.push(3);
    // cout<<sk.top();


    Stack<int> *sk = new Stack<int>;
    sk->push(1);
    sk->push(2);
    sk->push(3);
    sk->pop();
    cout<<sk->top();
    delete sk;
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读