//stringm.cpp //methods for class String //'+' and '==' operators are implemented as member functions #include "stringm.h" #include #include #include const int Max = 256; //member functions: //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; } //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; } //concatenates two Strings, leaving both of them unchanged String String::operator+(const String& s) { String temp; temp.length = length + s.length; temp.val = new char[temp.length+1]; assert(temp.val); strcpy(temp.val, val); strcat(temp.val, s.val); return temp; } //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 reference to nth element of string char& String::operator[](int n) { assert(n < length && n >= 0); return val[n]; } //nonmember functions: //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; }