类模版

//Stack.h
#ifndef _STACK_H_
#define _STACK_H_

template<typename T>
class Stack
{
private:
	int size;//栈中元素个数
	int top;//栈顶元素位置
	T *stackPtr;
public:
	Stack(int = 10);
	~Stack()
	{
		delete [] stackPtr;
	}
	bool push(const T&);
	bool pop(T&);
	bool isEmpty() const
	{
		return top == -1;
	}
	bool isFull() const
	{
		return top == size-1;
	}
};

template<typename T>
Stack<T>::Stack(int s)
	:size(s > 0 ? s : 10),
	 top(-1),
	 stackPtr(new T[size])
{
	//empty body
}

template<typename T>
bool Stack<T>::push(const T &pushValue)
{
	if(!isFull())
	{
		stackPtr[++top] = pushValue;
		return true;
	}
	return false;
}

template<typename T>
bool Stack<T>::pop(T &popValue)
{
	if(!isEmpty())
	{
		popValue = stackPtr[top--];
		return true;
	}
	return false;
}
#endif

//testMain.cpp

#include <iostream>
using namespace std;
#include "Stack.h"

int main()
{
	Stack<double> doubleStack(5);
	double doubleValue = 1.2;
	cout << "Pushing elements onto doubleStack" << endl;
	while(doubleStack.push(doubleValue))
	{
		cout << doubleValue << ' ';
		doubleValue += 1.2;
	}
	cout << "\nStack is full.Cannot push " <<doubleValue 
		   << "\nPoping elements from doubleStack.\n";
	while(doubleStack.pop(doubleValue))
		cout << doubleValue << " ";
	cout << "\nstack is empty,Cannot pop." << endl;

	Stack<int> intStack;
	int intValue = 1;
	cout << "Pushing elements onto intStack" << endl;
	while(intStack.push(intValue))
	{
		cout << intValue << ' ';
		intValue ++;
	}
	cout << "\nStack is full.Cannot push " <<intValue 
		   << "\nPoping elements from intStack.\n";
	while(intStack.pop(intValue))
		cout << intValue << " ";
	cout << "\nstack is empty,Cannot pop." << endl;

	system("pause >> cout");
	return 0;
}
//创建函数模版来测试类模版Stack<T>
#include <iostream>
#include <string>
using namespace std;
#include "Stack.h"

template <typename T>
void testStacks(Stack<T> theStack,
	                   T value,
					   T increment,
					   const string StackName)
{
	cout << "Pushing elements onto " << StackName << endl;
	while(theStack.push(value))
	{
		cout << value << " ";
		value += increment;
	}
	cout << "\nStack is full,Cannot push " << value
		   << "\nPoping elements from " << StackName << endl;
	while(theStack.pop(value))
	{
		cout << value << " ";
	}
	cout << "\nStack is empty,Cannot pop." << endl;
}

int main()
{
	Stack<double> doubleStack(5);
	Stack<int> intStack;
	
	testStacks(intStack,1,3,"intStack");
	testStacks(doubleStack,1.2,2.3,"doubleStack");
	system("pause >> cout");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值