此方法通过指针方式插入对象,释放时调用对象delete。
#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.
}
}