以OOP实现一个顺序栈为例, 介绍构造函数与析构函数
#include <iostream>
#include <iterator>
using namespace std;
/*
构造函数和析构函数
函数的名字和类名一样,没有返回值
*/
class SeqStack {
public:
//构造函数有参数,可重载
SeqStack(int size = 10) {
cout << this << " SeqStack()" << endl;
_pstack = new int[size];
_top = -1;
_size = size;
}
// void init(int size = 10) {
// _pstack = new int[size];
// _top = -1;
// _size = size;
// }
//析构函数不带参数,只能有一个,可手动调用释放堆内存
~SeqStack() {
cout << this << " ~SeqStack()" << endl;
delete[] _pstack;
_pstack = nullptr;
}
// void release() {
// delete[] _pstack;
// _pstack = nullptr;
// }
void push(int val) {
if (full())
resize();
_pstack[++_top] = val;
}
void pop() {
if (empty())
return;
--_top;
}
int top() { return _pstack[_top]; }
bool empty() { return _top == -1; }
bool full() { return _top == _size - 1; }
void resize() {
int* ptmp = new int[_size * 2];
for (int i = 0; i < _size; ++i) {
ptmp[i] = _pstack[i];
}
delete[] _pstack;
_pstack = ptmp;
_size += 2;
}
private:
int* _pstack; // 动态开辟数组,存储顺序栈的元素
int _top; //指向栈顶元素的位置
int _size; //数组扩容总大小
};
int main() {
// 1. 开辟内存
// 2. 调用构造函数
SeqStack s;
// s.init(5); //对象成员变量的初始化
for (int i = 0; i < 15; ++i) {
s.push(rand() % 100);
}
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
cout << endl;
// s.release(); //释放对象成员变量占用的外部堆内存(外部资源)
//出作用域,对象自动进行析构
SeqStack s1(50);
//堆上的一定要手动释放
SeqStack* ps = new SeqStack(60);
ps->push(70);
ps->push(80);
ps->pop();
cout << ps->top() << endl;
delete ps; //先调用ps->~SeqStack() 然后free(ps)
// 先构造的后析构,后构造的先析构
// 开始运行...
// 0x7fff9908e2d8 SeqStack()
// 63 59 90 27 62 21 49 92 86 35 93 15 77 86 83
// 0x7fff9908e2b0 SeqStack()
// 0x527510 SeqStack()
// 70
// 0x527510 ~SeqStack()
// 0x7fff9908e2b0 ~SeqStack()
// 0x7fff9908e2d8 ~SeqStack()
// 运行结束。
return 0;
}
标签:ps,SeqStack,函数,与析构,cout,C++,构造函数
From: https://www.cnblogs.com/anqwjoe/p/16660346.html