学习创建了一个堆栈类模板,然后将堆栈类模板实例化为一个字符串堆栈类。有几点问题需要注意:
1.因为模板不是函数,他们不能单独编译。模板必须与特定的模板实例化请求一起使用。为此,最简便的方法就是把所有模板信息放在一个头文件中,包括模板成员函数的实现。
2.在自己定义的cpp文件中必须将#include “stdafx.h”放在所有预处理指令的最上方,否则编译会出错。
3.仅仅声明一个函数而没有实现该函数,则会出现"fatal error LNK 1120: 无法解析的外部命令"这个链接错误。
源代码如下:
// stacktp.h a stack template
// 创建堆栈类模板
#ifndef STACKTP_H_
#define STACKTP_H_
template <class Type>
class Stack
{
private:
enum { MAX = 3 };
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 -- testing the template stack class
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cctype>
#include "stacktp.h"
using std::cin;
using std::cout;
using namespace std;
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;
}
运行效果如图:
果如图: