欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++ Primer Plus学习笔记 第十四章 类模板

程序员文章站 2022-03-09 09:26:36
...

跟函数模板差不多 我直接上代码吧

stacktp.h

#ifndef STACKTP_H_
#define STACKTP_H_

template<class Type>
class Stack
{
  private:
    enum {MAX = 10};
    Type items[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 & item)
{
  if (top < MAX)
  {
    items[top++] = item;
    return true;
  }
  else
  {
    return false;
  }
}

template<class Type>
bool Stack<Type>::pop(Type & item)
{
  if (top > 0)
  {
    item = items[--top];
    return true;
  }
  else
    return false;
}

#endif

stacktem.cpp

#include <iostream>
#include <string>
#include <cctype>
#include "stacktp.h"
using std::cin;
using std::cout;

int main()
{
  Stack<std::string> st;
  char ch;
  std::string po;
  cout << "Please enter A to add a purchase order,\n"
       << "P to 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\n";
                else
                  st.push(po);
                break;
      case 'p':
      case 'P': if (st.isempty())
                    cout << "stack already empty\n";
                else
                {
                  st.pop(po);
                  cout << "PO #" << po << " popped\n";
                  break;
                }
    }
    cout << "Please enter A to add a purchase order,\n"
         << "P to process a PO, or Q to quit.\n";
  }
  cout << "Bye\n";
  return 0;
}

这不适用于指针

关于指针栈明天说 

 

相关标签: C++ Primer Plus