OOC:en:2.4 An Application
来自 ChinaUnix Wiki
While we have not yet implemented strings, we are still ready to write a simple test program. String.h defines the abstract data type:
extern const void * String;
All our methods are common to all objects; therefore, we add their declarations to the memory management header file new.h introduced in section 1.4:
void * clone (const void * self); int differ (const void * self, const void * b); size_t sizeOf (const void * self);
The first two prototypes declare selectors. They are derived from the correspond- ing components of struct Class by simply removing one indirection from the declarator. Here is the application:
#include "String.h"
#include "new.h"
int main ()
{ void * a = new(String, "a"), * aa = clone(a);
void * b = new(String, "b");
printf("sizeOf(a) == %u\n", sizeOf(a));
if (differ(a, b))
puts("ok");
if (differ(a, aa))
puts("differ?");
if (a == aa)
puts("clone?");
delete(a), delete(aa), delete(b);
return 0;
}
We create two strings and make a copy of one. We show the size of a String object — not the size of the text controlled by the object — and we check that two different texts result in different strings. Finally, we check that a copy is equal but not identical to its original and we delete the strings again. If all is well, the pro- gram will print something like
sizeOf(a) == 8 ok
