The elements of the String
class are chacter strings. The following operations can be performed on
them:
1. Assignment from one String instance to another.
2. Type conversion of a String instance to a char *
3. Indexing.
4. etc.
The String class offers many advantages over the use of char *
- A string object is NOT a C-string. We often speak of char * variables in C as being "strings". A string object is not a char *, it is an instance of the String class.
1. Assignment (=) and comparison (==) have the meaning we would like them to have. (QUESTION: What meaning do they have for char *?).
2. Storage allocation and de-allocation are handled automatically.
3. Indexing limitations are handled automatically.
class String
{
private:
unsigned int Buffer_Len;
char *Buffer;inline void Get_Buffer( const unsigned int Max_Length );
public:
// Constructors.
String ( const char * Value = NULL );
String ( const String & Value );// Destructor.
~String ( ) { delete [ ] Buffer; }// Assignment operator.
const String & operator = ( const String & Value );// Get a single character.
char & operator [ ] ( unsigned int Index ) const;// Type cast to char *.
operator const char * const ( ) const { return Buffer; }// Get the length.
unsigned int Length ( ) { return strlen( Buffer ); }
private:
// Friends
friend int operator == (const String& lhs, const String& rhs);
friend int operator != (const String& lhs, const String& rhs);
friend int operator< (const String& lhs, const String& rhs);
friend int operator> (const String& lhs, const String& rhs);};
- The underlying representation of a string object is as a char* (called Buffer) - it's private.
- The String class also stores the length of the buffer as a private unsigned int.