泛型编程:模板类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_21107433/article/details/82084070
#include <iostream>
#include <vector>
using namespace std;

template<typename T>
class MyStack
{
public:
    MyStack();
    ~MyStack();
    void num();
    T top();
    void pop();
    void push(T t);
    void showStack();

private:
    vector<T>list;
};

template<typename T>
MyStack<T>::MyStack()
{

}

template<typename T>
MyStack<T>::~MyStack()
{

}

template<typename T>
void MyStack<T>:: num()
{
    cout << list.size() << endl;
}

template<typename T>
T MyStack<T>::top()
{
    return list[list.size()-1];
}

template<typename T>
void MyStack<T>::push(T t)
{
    list.push_back(t);
}

template<typename T>
void MyStack<T>::pop()
{
    list.pop_back();
}

template<typename T>
void MyStack<T>::showStack()
{
    for (int i = 0; i < list.size(); i++)
        cout << list[i] << " ";
    cout << endl;
}
int main()
{
    MyStack<int> intStack;
    intStack.push(1);
    intStack.push(2);
    intStack.push(3);
    intStack.showStack();
    intStack.pop();
    intStack.showStack();

    cout << "******************************" << endl;
    MyStack<double> doubleStack;
    doubleStack.push(1.12);
    doubleStack.push(2.23);
    doubleStack.showStack();
    doubleStack.pop();
    doubleStack.showStack();

    system("pause");
    return 0;
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/sinat_21107433/article/details/82084070