Smalltalk-like Classes Example
To orient ourselves, we always like to start with an example. The following example uses a
SortedCollection to store and order a set of
RWCollectableStrings.
SortedCollection is actually a typedef for the Smalltalk-like collection class
RWBinaryTree. Objects inserted into it are stored in order according to their relative values as returned by the virtual function
compareTo(). (See
Add Definitions for Virtual Functions.)
Here is the code:
#define RW_STD_TYPEDEFS 1 //1
#include <rw/bintree.h>
#include <rw/collstr.h> //2
#include <rw/rstream.h>
using std::cout;
using std::endl;
int main(){
// Construct an empty SortedCollection
SortedCollection sc; //3
// Insert some RWCollectableStrings:
sc.insert(new RWCollectableString("George")); //4
sc.insert(new RWCollectableString("Mary"));
sc.insert(new RWCollectableString("Bill"));
sc.insert(new RWCollectableString("Throkmorton"));
// Now iterate through the collection printing all members:
RWCollectableString* str; //5
SortedCollectionIterator sci(sc); //6
while( str = (RWCollectableString*)sci() ) //7
cout << *str << endl; //8
sc.clearAndDestroy();
return 0;
}
Program Output:
Bill
George
Mary
Throkmorton
The following explains the code line-by-line:
When run, the program prints out the four collected strings in order; for class
RWCollectableString, this means lexicographical order.