标签:
class my_string{ friend ostream& operator<< (ostream&,my_string&); public: my_string():data(NULL) { } my_string(const char* str) { int n = strlen(str); data = new char[n+1]; strcpy(data,str); } my_string(const my_string &other):data(NULL) { *this = other; } my_string& operator=( const my_string& other) { if(this == &other) return *this; delete []data; int n = other.size(); data = new char[n+1]; strcpy(data,other.data); return *this; } my_string operator+(const my_string& other)const { int n = strlen(data); int m = strlen(other.data); my_string newstr; newstr.data = new char[m+n+1]; for(int i = 0; i < n; i++) newstr[i] = data[i]; for(int i = n; i < n+m; i++) newstr[i] = other.data[i-n]; newstr[m+n] = NULL; return newstr; } bool operator==(const my_string& other) { return !strcmp(data,other.data); } char& operator[](int pos) { assert(pos < size()); return data[pos]; } int size()const { return strlen(data); } ~my_string() { delete[] data; } private: char *data; }; ostream& operator<<(ostream& os,my_string& str) { os << str.data; return os; }
标签:
原文地址:http://www.cnblogs.com/gcczhongduan/p/4199638.html