Bruce Eckel's Thinking in C++, 2nd Ed | Contents | Prev | Next |
//: C06:Stack3.h // With constructors/destructors #ifndef STACK3_H #define STACK3_H class Stack { struct Link { void* data; Link* next; void initialize(void* Data, Link* Next); } * head; public: Stack(); ~Stack(); void push(void* Data); void* peek(); void* pop(); }; #endif // STACK3_H ///:~
//: C06:Stack3.cpp {O} // Constructors/destructors #include <cstdlib> #include "../require.h" #include "Stack3.h" using namespace std; void Stack::Link::initialize( void* Data, Link* Next) { data = Data; next = Next; } Stack::Stack() { head = 0; } void Stack::push(void* Data) { // Can't use a constructor with malloc! Link* newLink = (Link*)malloc(sizeof(Link)); require(newLink); newLink->initialize(Data, head); head = newLink; } void* Stack::peek() { return head->data; } void* Stack::pop() { if(head == 0) return 0; void* result = head->data; Link* oldHead = head; head = head->next; free(oldHead); return result; } Stack::~Stack() { Link* cursor = head; while(head) { cursor = cursor->next; free(head->data); // Assumes malloc! free(head); head = cursor; } } ///:~
//: C06:Stktst3.cpp //{L} Stack3 // Constructors/destructors #include <cstdio> #include <cstdlib> #include <cstring> #include "../require.h" #include "Stack3.h" using namespace std; int main(int argc, char* argv[]) { requireArgs(argc, 1); // File name is argument FILE* file = fopen(argv[1], "r"); require(file); #define BUFSIZE 100 char buf[BUFSIZE]; Stack textlines; // Constructor called here // Read file and store lines in the Stack: while(fgets(buf, BUFSIZE, file)) { char* string = (char*)malloc(strlen(buf) + 1); require(string); strcpy(string, buf); textlines.push(string); } // Pop lines from the Stack and print them: char* s; while((s = (char*)textlines.pop()) != 0) { printf("%s", s); free(s); } } // Destructor called here ///:~