// An implementation of dynamically allocated strings. #include #include #include const int max_len = 255; class string { public: string() { len = 255; s = new char[255]; } // constructor, inline string(int n) { s = new char[n + 1]; len = n; } // constructor, inline string(const char* p); // constructor // // Because we do not want to deallocate the space // that is created by operator+(), we do not use the // destructor in this program. Later, after we learn // how to overload the = operator, we will be able to // use it without difficulty. To see what the effects // are, experiment by first running this program // without the destructor and then with it. // // ~string() { delete []s; } // destructor, inline // void assign(const char* t) { strcpy(s, t); len = strlen(t); } int length() { return len; } void print() { cout << s << "\nLength: " << len << "\n\n"; } friend string operator+(const string& a, const string& b); private: char* s; int len; }; int main() { string a, b(10), c("I came by horse."); cout << "\n"; a.assign("By horse?"); b.assign("Yes, by horse."); a = c + " " + a; c = a + " " + b; a.print(); b.print(); c.print(); return 0; } string::string(const char* p) { len = strlen(p); s = new char[len + 1]; strcpy(s, p); } string operator+(const string& a, const string& b) // overload + { string tmp(a.len + b.len - 1); tmp.assign(a.s); if (tmp.len < max_len) strcat(tmp.s, b.s); else { cerr << "\nMax length exceeded - bye!\n\n"; exit(1); } return tmp; }