C++学习日志之运用类模板编写栈操作的实例

C++的类模板为生成通用的类声明提供了一种更好的方法。模板提供参数化类型,即能够将类型名作为参数传递给接收方来建立类或函数。采用类模板时,使用模板定义替换类声明,使用模板成员函数替换类的成员函数 模板类这样开头  template<class Type> 关键字template 告诉编译器,将要定义一个模板。尖括号中的内容相当于函数的参数列表。可以把关键字class 看作是变量的类型名,该变量接受类型作为其值,把type看作该变量的名称。模板的具体实现被称为实例化或具体化,不能将模板成员函数放在独立的实现文件中,由于模板不是函数,不能独立编译。模板必须与特定的模板实例化请求一起使用。
好了,看代码吧。

stack.h

#ifndef STUENT_H_
#define STUDENT_H_
template <class Type>
class Stack{
private:
    enum{MAX=10};
    Type item[MAX];
    int top;
public:
    Stack();
    bool isempty();
    bool isfull();
    bool push(const Type &item);
    bool pop(Type & item);
};
template <class Type>
Stack<Type>::Stack()
{
    top=0;
}
template <class Type>
bool Stack<Type>::isempty()
{
    return top==0;
}
template <class Type>
bool Stack<Type>::isfull()
{
    return top==MAX;
}
template <class Type>
bool Stack<Type>::push(const Type & items)
{
    if(top<MAX)
    {
        item[top++]=items;
        return true;
    }
    else
        return false;
}
template <class Type>
bool Stack<Type>::pop(Type & items)
{
    if(top>0)
    {
        items=item[--top];
        return true;
    }
    else
        return false;
}
#endif // STUENT_H_



main.cpp

#include<iostream>

#include"student.h"
#include"cctype"
#include"cstring"
using std::cin;
using std::cout;
using std::endl;
int main()
{
    Stack<std::string> st;
    char ch;
    std::string po;
    cout << "please enter a to add a purchase order,\n p ot process a po, or q to quit.\n";
    while(cin>>ch&&std::toupper(ch)!='q')
    {
        while(cin.get()!='\n')
            continue;
        if(!std::isalpha(ch))
        {
            cout << '\a';
            continue;
        }
        switch(ch)
        {
        case 'A':
        case 'a':
            cout << "enter a po number to add: ";
            cin >> po;
            if(st.isfull())
                cout << "stack already full" << endl;
            else
                st.push(po);
            break;
        case 'p':
        case 'P':
            if(st.isempty())
                cout << "stack already empty." << endl;
            else{
                st.pop(po);
                cout << "PO # " << po << "popped\n";
                break;
            }

        }
        cout << "please enter a to add a puchase oredr,\n p to process a po, or q to quit." <<endl;
    }
    cout <<"bye" << endl;
    return 0;
}



                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值