Here is an example that uses an RWGStack , a generic stack, to store a set of pointers to ints in a last-in, first-out (LIFO) stack. We will go through it line-by-line and explain what is happening:
#include <rw/gstack.h> //1 #include <rw/rstream.h> //2 declare(RWGStack, int) //3 main(){ RWGStack(int) gs; //4 gs.push(new int(1)); //5 gs.push(new int(2)); //6 gs.push(new int(3)); //7 gs.push(new int(4)); //8 cout << "Stack now has " << gs.entries() << " entries\n"; //9 int* ip; //10 while( ip = gs.pop() ) //11 { cout << *ip << "\n"; //12 delete ip; } return 0; }
Program Output:
Stack now has 4 entries 4 3 2 1
Each line of the program is detailed below.
//1 | This #include defines the preprocessor macro RWGStackdeclare(type). This macro is an elaborate and ugly-looking thing that continues for many lines and describes how a generic stack of objects of type type should behave. Mostly, the macro serves as a restricted interface to the underlying implementation, which is a singly-linked list, class RWSlist. It is restricted because it can use only those member functions of RWSlist appropriate to stacks, and insert into the stack only items of type type. |
//2 | <rw/rstream.h> is a special Rogue Wave header file that includes <iostream.h> with a suffix that depends on your compiler. |
//3 | This line invokes the macro declare, which is defined in the header file <generic.h> supplied with your compiler. If called with arguments declare(Class, type), it calls the macro Classdeclare with argument type. In this case, the macro RWGStackdeclare, defined in <rw/gstack.h>, will be called with argument int.
In other words, the result of calling the declare(RWGStack, int) macro is to create a new class especially for your program. For all practical purposes, its name is RWGStack(int), a stack of pointers to ints. |
//4 | At this line an instance gs of the new class RWGStack(int) is created. |
//5-//8 | Four ints are created off the heap and inserted into the stack. After statement 8 executes, a pointer to the int 4 will be at the top of the stack, and a pointer to the int 1 at the bottom. |
//9 | The member function entries() of class RWGStack(int) is called to verify how many items are on the stack. |
//10 | A pointer to an int is declared and defined. |
//11 | The stack is popped until empty. The member function pop() will return and remove a pointer to the item on the top of the stack. If there are no more items on the stack it will return zero, causing the while loop to terminate. |
//12 | Each item is dereferenced and printed. |