// 简易stack
#include<cstdio>
#include<iostream>
using namespace std;
template<typename T>
class stack {
private:
T* pstack; int capacity, top,size=0;
public:
stack(int c = 5):top(-1), capacity(c) {
pstack = new T[capacity];
cout << "stack init" << endl;
}
// 拷贝构造函数
stack(const stack<T> & s):capacity(s.capacity),top(s.top) // 在stack 内部,可以访问其私有成员 //(以class封装,而不是以对象来封装
{
pstack = new T[capacity];
for (int i = 0; i < capacity; ++i)
{
pstack[i] = s.pstack[i];
}
cout << "stack copy" << endl;
}
// 移动拷贝构造函数
// 带右值引用参数的拷贝构造函数 目的:把即将销毁的内存保护起来,接着用
stack(stack<T>&& s) noexcept{
cout << "stack&&" << endl; /*此处没有重新开辟内存拷贝数据,把s的资源直接给当前对象,再把s置空*/
capacity = s.capacity;
top = s.top;
pstack = s.pstack;
s.pstack = NULL; // 这里刚刚写错了s=NULL导致一直报错
}
~stack() {
delete[] pstack;
cout << "stack delete" << endl;
}
// 重载=运算符
stack<T>& operator=(const stack<T>& s);
stack<T>& operator=(stack<T>&& s)noexcept;
T pop();
void push(T const& e);
int get_size();
// get_top表示获得栈顶元素
T get_top();
void show();
};
template<typename T> stack<T>& stack<T>::operator=(stack<T>&& s)noexcept { // ERROR:operator函数重定义
if (&s == this)
return *this;
if (this != NULL)
delete[] pstack;
// 内存转接
capacity = s.capacity;
top = s.top;
pstack = s.pstack;
s.pstack = NULL;
cout << "operator=&&" << endl;
return *this;
}
template<typename T> stack<T>& stack<T>::operator=(const stack<T>& s)
{
// 自身赋值问题
if (&s == this) // 不能 s==*this,因为没有重载等号运算符,两个对象之间不能相互比较
return*this;
if (this != NULL)
delete[] pstack; // 释放原有的空间内存
pstack = new T[s.capacity];
capacity = s.capacity;
top = s.top;
for (int i = 0; i < capacity; ++i)
{
pstack[i] = s.pstack[i];
}
cout << "stack operator=" << endl;
return *this;
}
template<typename T> int stack<T>::get_size()
{
return capacity;
}
template<typename T> T stack<T>::get_top()
{
return pstack[top];
}
template<typename T> void stack<T>::push(T const&e)
{
pstack[++top] = e;
size++;
}
template<typename T> T stack<T>::pop()
{
size--;
return pstack[top--];
}
template<typename T> void stack<T>::show()
{
for (int i = 0; i < size; ++i)
{
cout << pstack[i] << " ";
}
cout << endl;
}
// 以下为函数************************************************************************
template<typename T> stack<T> get_stack1(stack<T>& s) {
stack<T> temp(s.get_size());
return temp;
}
// 右值引用:引用临时对象
template<typename T> stack<T> get_stack2(stack<T>&& s) {
stack<T> temp(s.get_size());
return temp;
}
int main()
{
stack<int> s;
s = get_stack1<int>(s);
// s = get_stack2<int>(s); //Error:没有与参数列表匹配的 函数模板 "get_stack2" 实例,不能传一个左值给右值引用
s.push(1);
s.push(3);
s.show();
s.pop();
s.show();
}