// This program demonstrates two overloaded operators: // overloaded assignment, and overloaded output #include #include using std::ostream; class string { public: string() : buf( new char[1]) { buf[0] = '\0'; } string(int n) : buf(new char[n+1]) {} string(const char* s) : buf(new char[strlen(s)+1]) { strcpy(buf, s); } string(const string& s) : buf(new char[s.size()+1]) { strcpy(buf, s.buf); } int size() const { return strlen(buf); } const char* getBuf() const { return buf; } void setBuf(const char* b) { delete [] buf; buf = new char[strlen(b)+1]; strcpy(buf, b); } const string& operator=(const string& rhs) { if (&rhs != this) { setBuf(rhs.buf); } return *this; } private: char *buf; }; ostream& operator<<(ostream &lhs, const string &s) { return lhs << s.getBuf(); } int main() { string dog("dog"); string x; x = dog; dog.setBuf("Abraham Lincoln"); std::cout << x << std::endl; }