home *** CD-ROM | disk | FTP | other *** search
- #include <stdio.h>
- #include <string.h>
-
- class String {
- char *str;
- static int count;
- public:
- String() { count++; str = new char; *str = 0; }
- String( char * );
- ~String() { delete str; }
- operator char *();
- int operator < (String s) { return strcmp(str, s.str) < 0; }
- void print() { printf("%s", str); }
-
- friend int operator < (String, String);
- friend void report() ;
- };
-
- String::String(char *s)
- {
- count++;
- str = new char[strlen(s) + 1];
- strcpy(str, s);
- }
-
- String::operator char*() {
- char *p = new char[strlen(str) + 1];
- strcpy (p, str);
- return p; //use only a copy of str for protection
- }
-
- int operator < (String s1, String s2)
- {
- return strcmp (s1.str, s2.str);
- }
-
- void report()
- {
- printf("Report on String usage: " );
- printf(" %d Strings created\n", String::count);
- }
-
- main()
- {
- String s0 ;
- String s1 ("s1 == \"Hello C\"\n");
- String s2 ("s2 == \"Hello C++\"\n");
- String *sp = new String( "Hello world!" );
-
- char *cp = (char *) *sp; //same as *cp = *sp
-
- if ( !strcmp(cp, (char *) *sp) )
- printf("char *cp == (char *) *sp == \"%s\"\n", cp);
-
- s1.print();
- s2.print();
-
- if(s1.operator < (s2))
- printf("s1.operator < (s2)\n");
- if(operator < (s1, s2))
- printf("operator < (s1, s2)\n");
- report();
- }
- /* output:
-
- char *cp == (char *) *sp == "Hello world!"
- s1 == "Hello C"
- s2 == "Hello C++"
- s1.operator < (s2)
- operator < (s1, s2)
- Report on String usage: 4 Strings created
-
- */