#include #include using namespace std; class String { char* str; public: String( const char* ); ~String(); const char* getValue(); bool lessThan( const String& ); void concat( const String& ); }; void main( void ) { String first( "hello " ), second( "world" ); cout << first.getValue() << (first.lessThan( second ) ? " < " : " >= ") << second.getValue() << endl; cout << second.getValue() << (second.lessThan( first ) ? " < " : " >= ") << first.getValue() << endl; first.concat( second ); cout << first.getValue() << endl; } // String ctor: hello // String ctor: world // hello < world // world >= hello // hello world // String dtor: world // String dtor: hello world String::String( const char* in ) { str = new char[strlen(in) + 1]; strcpy( str, in ); cout << "String ctor: " << str << endl; } String::~String() { cout << "String dtor: " << str << endl; delete str; } const char* String::getValue() { return str; } bool String::lessThan( const String& other ) { return strcmp( str, other.str ) < 0; } void String::concat( const String& other ) { char* ptr = new char[strlen(str) + strlen(other.str) + 1]; strcpy( ptr, str ); strcat( ptr, other.str ); delete str; str = ptr; } #if 0 #include #include #include using namespace std; bool operator < ( const class String&, const class String& ); class String { char* str; public: String( const char* ); ~String(); string operator () ( char ); friend bool operator < ( const String&, const String& ); void operator += ( const String& ); }; void main( void ) { String first( "hello " ), second( "world" ); cout << first( '-' ) << ((first < second ) ? " < " : " >= ") << second( '=' ) << endl; cout << second( '=' ) << ((second < first ) ? " < " : " >= ") << first( '-' ) << endl; first += second; cout << first( '-' ) << endl; } // String ctor: hello // String ctor: world // -hello - < =world= // =world= >= -hello - // -hello world- // String dtor: world // String dtor: hello world String::String( const char* in ) { str = new char[strlen(in) + 1]; strcpy( str, in ); cout << "String ctor: " << str << endl; } String::~String() { cout << "String dtor: " << str << endl; delete str; } string String::operator () ( char ch ) { string s( str ); return ch + s + ch; } bool operator < ( const String& lhs, const String& rhs ) { return strcmp( lhs.str, rhs.str ) < 0; } void String::operator += ( const String& other ) { char* ptr = new char[strlen(str) + strlen(other.str) + 1]; strcpy( ptr, str ); strcat( ptr, other.str ); delete str; str = ptr; } #endif