类的前面需要有这样的头部:
template <typename T>
例子代码实现了一个Stack,代码如下:
#pragma once
template<typename T>
class Stack
{
public:
Stack(int = 10);//default contor(stack size 10)
//destructor
~Stack()
{
delete[] stackPtr;
}
bool push(const T&);//push an element onto the stack
bool pop(T&);//pop an element off the stack
//determin wheather Stack is empty
bool isEmpty()const
{
return top == -1;
}
//determin wheather Stack is full
bool isFull()const
{
return top == size - 1;
}
private:
int size;
int top;//location of the top element -1 means empty
T* stackPtr;//pointer to internal representation of the Stack;
};//end class template Stack
//contor template
template <typename T>
Stack<T>::Stack(int s)
:size(s > 0 ? s : 10),//validate size
top(-1),//Stack initially empty
stackPtr(new T[size])//allocate memory for elements
{
//empty body
}
//push element onto stack;if successful return true else return false
template <typename T>
bool Stack<T>::push(const T& pushValue)
{
if (!isFull())
{
stackPtr[++top] = pushValue;//place item on stack
return true;
}
return false;
}
//pop element off stack;if successful return true else return false
template <typename T>
bool Stack<T>::pop(T& popValue)
{
if (!isEmpty())
{
popValue = stackPtr[top--];
return true;
}
return false;
}
main()函数中来测试一下,看看效果。
// fig14_03StackTempTest.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include "Stack.h"
using namespace std;
int main()
{
Stack <double> doubleStack( 5 );//size 5
double doubleValue = 1.1;
cout << "Pushing elements onto doubleStack\n";
//push 5 elements onto stack
while (doubleStack.push(doubleValue))
{
cout << doubleValue << ' ';
doubleValue += 1.1;
}//end while
cout << "\nStack is full.Can not push " << doubleValue << "\n\nPoping element from doubleStack\n";
//pop element from doubleStack
while (doubleStack.pop(doubleValue))
{
cout << doubleValue << ' ';
}
cout << "\nStack is empty.Can not pop\n";
Stack <int> intStack;//default size 10
int intValue = 1;
cout << "Pushing elements onto intStack\n";
//push 10 elements onto stack
while (intStack.push(intValue))
{
cout << intValue << ' ';
intValue += 1;
}//end while
cout << "\nStack is full.Can not push " << intValue << "\n\nPoping element from intStack\n";
//pop element from doubleStack
while (intStack.pop(intValue))
{
cout << intValue << ' ';
}
cout << "\nStack is empty.Can not pop\n";
}
实现了两种Stack,doubleStack 和intStack。