C++ Class Template (C++类模板)

头文件
 
  

// stacktp.h -- a stack template
#ifndef STACKTP_H_
#define STACKTP_H_
template <class Type>
class Stack
{
private:
enum {MAX = 10}; // constant specific to class
Type items[MAX]; // holds stack items
int top; // index for top stack item
public:
Stack();
bool isempty();
bool isfull();
bool push(const Type & item); // add item to stack
bool pop(Type & item); // pop top into 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



C++文件:

 
  

// stacktem.cpp -- testing the template stack class
#include <iostream>
#include <string>
#include <cctype>
#include "stacktp.h"
using std::cin;
using std::cout;
int main()
{
Stack<std::string> st; // create an empty stack
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;
}



运行结果:
 
   

Please enter A to add a purchase order,
P to process a PO, or Q to quit.
A
Enter a PO number to add: CAT
Please enter A to add a purchase order,
P to process a PO, or Q to quit.
a
Enter a PO number to add: mouse
Please enter A to add a purchase order,
P to process a PO, or Q to quit.
A
Enter a PO number to add: SNAKE
Please enter A to add a purchase order,
P to process a PO, or Q to quit.
P
PO #SNAKE popped
Please enter A to add a purchase order,
P to process a PO, or Q to quit.
P
PO #mouse popped
Please enter A to add a purchase order,
P to process a PO, or Q to quit.
P
PO #CAT popped
Please enter A to add a purchase order,
P to process a PO, or Q to quit.
P
stack already empty
Please enter A to add a purchase order,
P to process a PO, or Q to quit.
q
Bye



分析:
As with template functions, you
preface a template class with code that has the following form:
template <class Type>
The keyword template informs the compiler that you’re about to define a template. The part
in angle brackets is analogous to an argument list to a function. You can think of the keyword
class as serving as a type name for a variable that accepts a type as a value, and of Type as
representing a name for this variable.
Using class here doesn’t mean that Type must be a class; it just means that Type serves as a
generic type specifier for which a real type will be substituted when the template is used.
Newer C++ implementations allow you to use the less confusing keyword typename instead of
class in this context:
template <typename Type>  // newer choice
You can use your choice of generic type name in the Type position; the name rules are the
same as those for any other identifier. Popular choices include T and Type; in this case, you
should use the latter. When a template is invoked, Type will be replaced with a specific type
value, such as int or string.
It’s important to realize that these templates are not class and member function definitions. Rather, they are
instructions to the C++ compiler about how to generate class and member function definitions. 
Because the templates aren’t functions, they can’t be compiled
separately. Templates have to be used in conjunction with requests for particular instantiations
of templates. The simplest way to make this work is to place all the template information in a
header file and to include the header file in the file that will use the templates.
 Merely including a template in a program doesn’t generate a template class. You have to ask for
an instantiation. To do this, you declare an object of the template class type, replacing the
generic type name with the particular type you want. For example, here’s how you would cre-
ate two stacks, one for stacking ints and one for stacking string objects:
Stack<int> kernels;          // create a stack of ints
Stack<string> colonels;    // create a stack of string objects
Seeing these two declarations, the compiler will follow the Stack<Type> template to generate
two separate class declarations and two separate sets of class methods. The Stack<int> class
declaration will replace Type throughout with int, and the Stack<string> class declaration
will replace Type throughout with string. Of course, the algorithms you use have to be con-
sistent with the types. The Stack class, for example, assumes that you can assign one item to
another. This assumption is true for basic types, structures, and classes (unless you make the
assignment operator private) but not for arrays.
Generic type identifiers such as Type in the example are called type parameters, meaning that
they act something like variables, but instead of assigning a numeric value to a type parameter,
you assign a type to it. So in the kernels declaration, the type parameter Type has the
value int.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值