C++和C语⾔实现Stack对⽐⾯向对象三⼤特性:封装、继承、多态,下⾯的对⽐我们可以初步了解⼀下封装。 通过下⾯两份代码对⽐,我们发现C++实现Stack形态上还是发⽣了挺多的变化,底层和逻辑上没啥变 化。
• C++中数据和函数都放到了类⾥⾯,通过访问限定符进⾏了限制,不能再随意通过对象直接修改数 据,这是C++封装的⼀种体现,这个是最重要的变化。这⾥的封装的本质是⼀种更严格规范的管 理,避免出现乱访问修改的问题。当然封装不仅仅是这样的,我们后⾯还需要不断的去学习。‘
• C++中有⼀些相对⽅便的语法,⽐如Init给的缺省参数会⽅便很多,成员函数每次不需要传对象地址,因为this指针隐含的传递了,⽅便了很多,使⽤类型不再需要typedef⽤类名就很⽅便
//c语言实现stack
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int DataType;
typedef struct Stack
{
DataType* a;
int top;
int capacity;
}ST;
void Init(ST* ps)
{
assert(ps);
ps->a = nullptr;
ps->top = 0;
ps->capacity = 0;
}
void Destroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = nullptr;
ps->top = ps->capacity = 0;
}
void Push(ST* ps, DataType x)
{
assert(ps);
if (ps->top = ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
DataType* tmp = (DataType*)realloc(ps->a, newcapacity * sizeof(DataType));
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
bool Empty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
DataType Top(ST* ps)
{
assert(ps);
assert(!Empty(ps));
return ps->a[ps->top - 1];
}
void Pop(ST* ps)
{
assert(ps);
assert(!Empty(ps));
ps->top--;
}
int Size(ST* ps)
{
assert(ps);
return ps->top;
}
int main()
{
ST s;
Init(&s);
Push(&s, 1);
Push(&s, 2);
Push(&s, 3);
Push(&s, 4);
while (!Empty(&s))
{
printf("%d\n", Top(&s));
Pop(&s);
}
Destroy(&s);
return 0;
}
//C++实现Stack
#include<iostream>
#include<assert.h>
using namespace std;
typedef int DataType;
class Stack
{
public:
//成员函数
void Init(int n = 4)
{
_a = (DataType*)malloc(sizeof(DataType) * n);
if (nullptr == _a)
{
perror("malloc申请空间失败");
return;
}
_capacity = n;
_top = 0;
}
void Push(DataType x)
{
if (_top == _capacity)
{
int newcapacity = _capacity * 2;
DataType* tmp = (DataType*)realloc(_a, newcapacity *sizeof(DataType));
if (tmp == nullptr)
{
perror("realloc fail");
return;
}
_a = tmp;
_capacity = newcapacity;
}
_a[_top++] = x;
}
void pop()
{
assert(_top > 0);
--_top;
}
bool Empty()
{
return _top == 0;
}
int Top()
{
assert(_top > 0);
return _a[_top - 1];
}
void Destroy()
{
free(_a);
_a = nullptr;
_top = _capacity = 0;
}
private:
//成员变量
DataType* _a;
size_t _capacity;
size_t _top;
};
int main()
{
Stack s;
s.Init();
s.Push(1);
s.Push(2);
s.Push(3);
while (!s.Empty())
{
cout << s.Top() << endl;
s.pop();
}
s.Destroy();
return 0;
}