zoukankan      html  css  js  c++  java
  • 类模板使用示例(五) 非类型类模板参数

    Stack4.hpp的代码如下:

    #ifndef STACK4_HPP
    #define STACK4_HPP
    
    #include <iostream>
    #include <vector>
    #include <stdexcept>
    
    template <typename T, int MAXSIZE>
    class Stack
    {
    public:
        Stack();
        void push(T const&);
        void pop();
        T top() const;
        bool empty() const
        {
            return 0 == numElems;
        }
    
        bool full() const
        {
            return MAXSIZE == numElems;
        }
    private:
        T elems[MAXSIZE];
        int numElems;
    };
    
    template <typename T, int MAXSIZE>
    Stack<T, MAXSIZE>::Stack()
    : numElems(0)
    {
    
    }
    
    template <typename T, int MAXSIZE>
    void Stack<T, MAXSIZE>::push(T const& elem)
    {
         if (full())
        {
            throw std::out_of_range("Stack<>::push(): stack is full");
        }
    
        elems[numElems] = elem;
        ++numElems;
    }
    
    template <typename T, int MAXSIZE>
    void Stack<T, MAXSIZE>::pop()
    {
        if (empty())
        {
            throw std::out_of_range("Stack<>::pop(): empty stack");
        }
    
        --numElems;
    }
    
    template <typename T, int MAXSIZE>
    T Stack<T, MAXSIZE>::top() const
    {
        if (empty())
        {
            throw std::out_of_range("Stack<>::top(): empty stack");
        }
    
        return elems[numElems-1];
    }
    
    #endif // STACK4_HPP

    测试代码main.cpp:

    #include <iostream>
    #include <string>
    #include <deque>
    #include <cstdlib>
    #include <typeinfo>
    #include "Stack4.hpp"
    
    using namespace std;
    
    int main()
    {
       try
        {
            Stack<int, 20> int20Stack;
            int20Stack.push(7);
            cout << int20Stack.top() << endl;
            int20Stack.pop();
    
            Stack<int, 40> int40Stack;
    
            cout << "
    The type of int20Stack: " << typeid(int20Stack).name() << endl
                 << "The type of int40Stack: " << typeid(int40Stack).name() << endl;
    
            Stack<string, 40> string40Stack;
            string40Stack.push("Hello");
            cout << endl << string40Stack.top() <<endl;
            string40Stack.pop();
            string40Stack.pop();
        }
        catch (std::exception const& ex)
        {
            cerr << "Exception: " << ex.what() << endl;
            return EXIT_FAILURE;// n stdlib.h
        }
    
        return 0;
    }

    结果:

  • 相关阅读:
    用移动硬盘代替DVD安装单系统Vista方法
    背完这444句,你的口语绝对不成问题了
    DataGridView 只能输入整数解决方案
    转载:Firefox的失败在中国几乎就是命中注定
    ZBlog 添加运行天数
    并行和串行通信
    ZBlog 添加收藏本站
    ITPUB调查高达42%的DBA由开发人员转变而成
    DataGridView 只能输入整数解决方案
    用移动硬盘代替DVD安装单系统Vista方法
  • 原文地址:https://www.cnblogs.com/AmitX-moten/p/4446082.html
Copyright © 2011-2022 走看看