|
|
|
| Test 1 | |
| Name: Stacky | Time: 1 hr |
|
Create a class which contains a stack the same as in the lesson, but this time you must create the stack using pointers, and only reference the class once to get the address of the stack in the class, do the processing in the main function. Only 1 function is allowed in the class itself. Make 2 functions - Push, and Pop in the program. Push the values - 5,67,83,22 onto the stack, then Pop the 2 out, outputting each value to the screen.
Hint: refer to lesson 6, the function in the class is used to retrive the memory location of the 1st element of the stack. Send down to the push and pop functions the Stack point address, not the address of the pointer. Once youve finished, I hope you will appreciate why we do the proccessing within the class - "Its alot easier!", but this is intended to get you more fluent (good) with pointers and addresses. Also, next time you make a stack, do it as in lesson 6, not like this, as its considered better programming to make it within the class, ie: make it an object. |
|
| Answer | ||
| Answer below - drag the cursor over the white space to highlight the answer | ||
| Test 1 | Stacky | Program , Source code |
#include <conio.h>
#include <iostream.h>
class My_class
{
private:
int Stack[20];
public:
int * Get_address()
{
return &Stack[0];
}
};
void Push(int a,int * top);
int Pop(int * top);
void main()
{
My_class Stack;
int *Pointer;
Pointer = Stack.Get_address(); //Get initial Stack Point address.
Push(5,Pointer);Pointer++; //Push 5, Point to the next element.
Push(67,Pointer);Pointer++; //Send down new Stack address.
Push(83,Pointer);Pointer++;
Push(22,Pointer); //Now pointing to element 4 (index 3).
cout << "Pop 1st one: " << Pop(Pointer) << endl;
Pointer--;
cout << "Pop 2nd one: " << Pop(Pointer) << endl;
getch();
}
void Push(int a,int * top) //top is the Stack Point
{
int *Pointer;
Pointer = top; //Now This Pointer also points to the stack
*Pointer = a;
}
int Pop(int * top)
{
int *Pointer;
Pointer = top; //All 3 pointers in all functions, point to the
return *Pointer; //Same given Stack point.
}
| ||
![]() |
![]() |
![]() |