//string3.cpp //methods for class String implemented with overloaded operators #include "string3.h" #include #include #include const int Max = 256; //default constructor String::String() { length = 0; val = new char; assert(val); *val = '\0'; } //conversion constructor from a C string String::String(const char *s) { length = strlen(s); val = new char[length+1]; assert(val); strcpy(val, s); } //copy constructor String::String(const String& s) { length = s.length; val = new char[length+1]; assert(val); strcpy(val, s.val); } //destructor String::~String() { delete [] val; } //returns the lenght of string int String::getlength() { return length; } //assignment operator String& String::operator=(const String& s) { if (this != &s) { delete [] val; length = s.length; val = new char[length+1]; assert(val); strcpy(val, s.val); } return *this; } //concatenation operator: concatenates two strings String& String::operator+=(const String& s) { length += s.length; char *temp = new char[length+1]; assert(temp); strcpy(temp, val); strcat(temp, s.val); delete [] val; val = temp; return *this; } //concatenates two Strings, leaving both of them unchanged String String::operator+(const String& s) { String result = *this; result += s; return result; } //equality operator: returns 1 if two strings are equal, //otherwise returns 0 int String::operator==(const String& s) { if (length != s.length) return 0; return strcmp(val, s.val) == 0; } //subscript operator: returns pointer to nth element of string, //if n is outside the length of string, returns NULL char* String::operator[](int n) { if (n > length-1 || n < 0) return NULL; return &val[n]; } //output operator: prints out string ostream& operator <<(ostream& os, String& s) { return os<>(istream& is, String& s) { char temp[Max], ch; is.get(temp, Max); for(;;) if (!is.get(ch) || ch == '\n') break; s.length = strlen(temp); s.val = new char[s.length+1]; assert(s.val); strcpy(s.val, temp); return is; }