类模板
- 类成为类名和类型参数的组合
- 无论是一般类还是模板类,只有调用到的成员函数,才会出现在符号表上。
#pragma once
#include <iostream>
#include <cstring>
using namespace std;
template<typename T>
class SeqStack { //模板名称 + 类型参数列表 = 类名称
private:
T* _pstack;
int _top;
int _size;
void resize();
public:
//构造和析构函数名可以不加类型参数列表,其它出现模板的地方都不能省略类型参数列表
SeqStack<T>(int size = 5);
SeqStack<T>(const SeqStack<T>& stack);
~SeqStack<T>();
SeqStack<T>& operator=(const SeqStack<T>& stack);
void push(const T& val);
void pop();
T top()const;//只读的方法时候设计为常方法
bool full()const;
bool empty()const;
int getlen()const { return _size; }
};
template<typename T>
void SeqStack<T>::resize()
{
_size *= 2;
T* tmp = new T[_size];
for (int i = 0; i < _top; i++)
{
tmp[i] = _pstack[i];
}
delete[]_pstack;
_pstack = tmp;
}
template<typename T>
SeqStack<T>::SeqStack<T>(int size)
: _pstack(new T[size])
, _size(size)
, _top(0)
{}
template<typename T>
SeqStack<T>::SeqStack<T>(const SeqStack<T>& stack)
:_size(stack._size)
, _top(stack._top)
{
delete[]_pstack;
_pstack = new T[_size];
for (int i = 0; i < _top; i++) {
_pstack[i] = stack._pstack[i];
}
}
template<typename T>
SeqStack<T>::~SeqStack<T>()
{
delete[]_pstack;
_pstack = nullptr;
}
template<typename T>
SeqStack<T>& SeqStack<T>::operator=(const SeqStack<T>& stack)
{
if (&stack == this)
{
return *this;
}
delete[]_pstack;
_top = stack._top;
_size = stack._size;
_pstack = new T[_size];
for (int i = 0; i < _top; i++) {
_pstack[i] = stack._pstack[i];
}
}
template<typename T>
void SeqStack<T>::push(const T& val)
{
if (full())
{
resize();
}
_pstack[top++] = val;
}
template<typename T>
void SeqStack<T>::pop()
{
if (empty())
{
return;
}
_top--;
}
template<typename T>
T SeqStack<T>::top()const
{
if (empty())
{
return;
}
return _pstack[--top];
}
template<typename T>
bool SeqStack<T>::full()const
{
if (top == _size);
}
template<typename T>
bool SeqStack<T>::empty()const
{
return(_top == 0);
}
int main()
{
SeqStack<int> s1;
cout << s1.getlen() << endl;
return 0;
}
标签:SeqStack,const,17,top,pstack,stack,模板,size
From: https://www.cnblogs.com/sio2zyh/p/17968393