C++大学教程(第七版)Chapter14.4类模板-fig14_03

类的前面需要有这样的头部:

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值