// FIG7_5.CPP // Friends can access private members of a class. #include // Modified Count class class Count { friend void setX(Count &, int); // friend declaration public: Count() { x = 0; } // constructor void print() const { cout << x << endl; } // output private: int x; // data member }; // Can modify private data of Count because // setX is declared as a friend function of Count void setX(Count &c, int val) { c.x = val; // legal: setX is a friend of Count } main() { Count object; cout << "object.x after instantiation: "; object.print(); cout << "object.x after call to setX friend function: "; setX(object, 8); // set x with a friend object.print(); return 0; } --------------------------------------------------------- // TSTACK1.H // Simple template class Stack #ifndef TSTACK1_H #define TSTACK1_H #include template class Stack { public: Stack(int = 10); // default constructor (stack size 10) ~Stack() { delete [] stackPtr; } // destructor int push(const T&); // push an element onto the stack int pop(T&); // pop an element off the stack int isEmpty() const { return top == -1; } // 1 if empty int isFull() const { return top == size - 1; } // 1 if full private: int size; // # of elements in the stack int top; // location of the top element T *stackPtr; // pointer to the stack }; // Constructor with default size 10 template Stack::Stack(int s) { size = s > 0 && s < 1000 ? s : 10; // reasonable size top = -1; // Stack is initially empty stackPtr = new T[size]; // space allocated for Stack elements } // Push an element onto the stack // return 1 if successful, 0 otherwise template int Stack::push(const T &item) { if (!isFull()) { stackPtr[++top] = item; // place item in Stack return 1; // push successful } return 0; // push unsuccessful } // Pop an element off the stack template int Stack::pop(T &popValue) { if (!isEmpty()) { popValue = stackPtr[top--]; // remove item from Stack return 1; // pop successful } return 0; // pop unsuccessful } #endif ------ // FIG12_3.CPP // Test driver for Stack template #include #include "tstack1.h" main() { Stack floatStack(5); float f = 1.1; cout << "Pushing elements onto floatStack" << endl; while (floatStack.push(f)) { // success (1 returned) cout << f << ' '; f += 1.1; } cout << endl << "Stack is full. Cannot push " << f << endl << endl << "Popping elements from floatStack" << endl; while (floatStack.pop(f)) // success (1 returned) cout << f << ' '; cout << endl << "Stack is empty. Cannot pop" << endl; Stack intStack; int i = 1; cout << endl << "Pushing elements onto intStack" << endl; while (intStack.push(i)) { // success (1 returned) cout << i << ' '; i += 1; } cout << endl << "Stack is full. Cannot push " << i << endl << endl << "Popping elements from intStack" << endl; while (intStack.pop(i)) // success (1 returned) cout << i << ' '; cout << endl << "Stack is empty. Cannot pop" << endl; return 0; } --------------------------------------------------------