stack的c++实现

#ifndef MYSTACK_H_
#define MYSTACK_H
#include<iostream>
using namespace std;
template<class T>
class Mystack
{
	enum{SIZE=10};
	int max_size;
	int count;
	T*data;
public:
	explicit Mystack(int ss = SIZE);
	Mystack(const Mystack& st);
	~Mystack(){ delete[]data; }
	bool isempty();	
	bool  push(const T&elem);
	bool  pop();
    friend ostream& operator<<(ostream &os, const Mystack<T>&stack2)
	{
		{
			if (stack2.count == 0)
			{
				os << "empty";
			}
			else
			{
				for (int i = 0; i < stack2.count; i++)
				{
					os << stack2.data[i] << ",";
				}
			}
			return os;
		}
	}
	Mystack& operator=(const Mystack& stack2);
};
template<class T>
Mystack<T>::Mystack(int ss)
{
	max_size = ss;
	count = 0;
	data = new T[max_size];
}
template<class T>
bool Mystack<T>::isempty()
{

	return count == 0;
}
template<class T>
Mystack<T>::Mystack(const Mystack& st)
{
	max_size = st.max_size;
	count = st.count;
	data = new T[max_size];
	for (int i = 0; i < count; i++)
		data[i] = st.data[i];
}
template<class T>
bool Mystack<T>::push(const T& elem)
{
	data[count++] = elem;
	return true;
}
template<class T>
bool Mystack<T>::pop()
{
	if (count == 0)
	{
		cout << "empty";
		return false;
	}
	count--;
	return true;

}
template<class T>
Mystack<T>& Mystack<T>::operator=(const Mystack<T>&stack2)
{
	if (this == &stack2)
		return *this;
	delete[]data;
	max_size = stack2.max_size;
	count = stack2.count;
	for (int i = 0; i < count; i++)
		data[i] = stack2.data[i];
	return *this;
}
#endif

猜你喜欢

转载自blog.csdn.net/fuck_you_sb/article/details/80657670