06從一個例項看資料抽象與封裝

惡魔布發表於2020-11-30

用C的方式實現棧

struct Link
{
	int data;
	struct Link* next;
};
struct Stack
{
	int size;
	struct Link* head;
};
void StackInit(struct Stack* stack);
void StackPush(struct Stack* stack, int data);
int StackPop(struct Stack* stack, int* data);	//返回型別為pop是否成功
int StackEmpty(struct Stack* stack);
void StackCleanup(struct Stack* stack);

用C++資料抽象的方式實現棧

  • 資料封裝,能保護內部資料不遭受外部破壞
  • 使得函式和資料成員更加緊密
class Stack
{
private:
	int size_;
	Link* head_;
	struct Link 
	{
		int data_;
		Link* next_;
		Link(int data, Link* next) : data_(data), next_(next);
	}
public:
	Stack():head_(NULL), size_(0)
	{}
	~Stack()
	{
		Link* tmp;
		while(head_)
		{
			tmp = head_;
			head_ = head_->next_;
			delete tmp;
		}
	}
	void Push(const int data)
	{
		Link* tmp = new Link(data, head_);
		head_ = tmp;
		++size_;
	}
	bool Empty()
	{
		return (size_ == 0);
	}
	bool Pop(int& data)
	{
		if(Empty())
		{
			return false;
		}
		Link* tmp = head_;
		data = head_->data_;
		head_ = head_->next_;
		delete tmp;
		--size_;

		return true;
	}
};

相關文章