C++ primer plus 编程练习12.4

stack.cpp:

#include
#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 
#include // 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中。

你可能感兴趣的:(c++,算法,开发语言)