C++ primer plus 编程练习12.4

stack.cpp:

#include<iostream>
#include"stack.h"
Stack::Stack(int n) {
	pitems = new Item[MAX];
	top = 0;
	for (; top < n; top++) {
		*pitems = top;
		pitems = pitems + 1;
	}
	size = n;
}
Stack::Stack(const Stack &st) {
	pitems = new Item[MAX];
	top = 0;
	for (; top < st.top; top++) {
		*pitems = st.pitems[top];
		pitems = pitems + 1;
	}
	size = st.size;
}
Stack::~Stack() {
	pitems = pitems - size;
	delete [] pitems;
	pitems = nullptr;
}
bool Stack::isempty() const {
	return(size == 0);
}
bool Stack::isfull() const {
	return(size == MAX);
}
bool Stack::push(const Item & item) {
	if (isfull()) return false;
	else {
		*pitems = item;
		top++;
		size++;
		pitems = pitems + 1;
		return true;
	}
}
bool Stack::pop(Item& item) {
	if (isempty()) return false;
	else {
		pitems = pitems - 1;
		item = *pitems;
		top--;
		size--;
		return true;
	}
}
Stack& Stack::operator=(const Stack &st) {
	if (this == &st) return *this;
	delete[] pitems;
	pitems = nullptr;
	pitems = new Item[MAX];
	size = st.size;
	top = st.top;
	return *this;
}

pe12_4.cpp

#include <iostream>
#include <cctype>// or ctype.h
#include "stack.h"
int main() {
	using namespace std;
	Stack st1(5); // create an empty stack
	char ch;
	unsigned long po;
	Stack st = st1;
	cout << "operator= succcess!" << endl;
	cout << "Please enter A to add a purchase order,\n" << "p to process a PO, or Q to quit.\n";
	while (cin >> ch && toupper(ch) != 'Q') {
		while (cin.get() != '\n')
			continue;
		if (!isalpha(ch)) {
			cout << '\a';
			continue;
		}
			switch (ch) {
			case 'A':
			case 'a': 
				if (st.isfull())
					cout << "stack already full\n";
				else
				{
					cout << "Enter a PO number to add:";
					cin >> po;
					st.push(po);
				}
				
				break;
			case 'p':
			case 'P': if (st.isempty())
				cout << "stack already empty n";
					else {
				st.pop(po);
				cout << "PO #" << po << " popped\n";
			}
					break;
		}
			
		cout << "please enter A to add a purchase order,\n" << "p to process a pO,or Q to quit.\n";
	}
	cout << "Bye\n";
	return 0;
}

知识学习:

如果在使用new 指针是改变了指针的地址 pitems =pitems+1;

Stack::Stack(int n) {
	pitems = new Item[MAX];
	top = 0;
	for (; top < n; top++) {
		*pitems = top;
		pitems = pitems + 1;
	}
	size = n;
}

delete 时 应该回到最初的地址。

Stack::~Stack() {
	pitems = pitems - size;
	delete [] pitems;
	pitems = nullptr;
}

以下析构函数 vs 会跳转到delete_scalar.cpp中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值