首页 > 其他 > 详细

模板栈的实现

时间:2015-11-02 00:10:16      阅读:316      评论:0      收藏:0      [点我收藏+]

以下代码来自《C++编程思想》P410-模板介绍

#include<fstream>
#include<iostream>
#include<string>
using namespace std;

template<class T>
class Stack
{
private:
	struct Link
	{
		T* data;
		Link* next;
		Link(T* da,Link* ne):data(da),next(ne){}
	}* head;
public:
	Stack():head(NULL){}
	~Stack()
	{
		while(head)
		{
			delete pop();        //释放data数据;
		}
	}
	void push(T* da)
	{
		Link* he = new Link(da,head);
		head = he;
	}
	T* peek()
	{
		return head ? head->data : 0;
	}
	T* pop()
	{
		if(head == NULL) return 0;
		T* da = head->data;
		Link* he = head;
		head = head->next;
		delete he;
		return da;
	}
};

class X
{
public:
	virtual ~X(){}	//用于调用子类对象的析构
};

int main(int argc, char* argc[])
{
	if(argc == 1)return 0;
	ifstream in(argv[1]);	//主函数参数列表
	Stack<string> textlines;
	string line;
	while(getline(in, line))
	{
		textlines.push(new string(line));
	}
	string* s;
	for(int i = 0; i < 10; ++i)
	{
		if((s = textlines.pop()) == 0) break;
		cout << *s <<endl;
		delete s;
	}
	Stack<X> xx;
	for(int j = 0; j < 10; ++j)
	{
		xx.push(new X);  //new X() is also ok.
	}
}

  

模板栈的实现

原文:http://www.cnblogs.com/tylerhuang/p/4928954.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!