MyString类
10
MyString operator+(const MyString& str1, const MyString& str2) { MyString temp; temp.length = str1.length + str2.length; temp.text = new char[ temp.length+1 ]; memcpy(temp.text, str1.text, str1.length); memcpy(&temp.text[str1.length], str2.text, str2.length); temp.text[temp.length] = 0; return temp; }
11
2
int operator<(const MyString& str) { return ( compare(str) < 0 );} int operator>(const MyString& str) { return ( compare(str) > 0 ); } int operator<=(const MyString& str) { return ( !(compare(str) > 0) ); } int operator>=(const MyString& str) { return ( !(compare(str) < 0) ); } int operator==(const MyString& str) { return ( compare(str) == 0 ); } int operator!=(const MyString& str) { return ( compare(str) != 0 ); }
8
MyString& MyString::operator=(const MyString& str) { length = str.length; delete text;
text = new char[length+1]; memcpy(text, str.text, length+1); return *this;
}
9
更完善的代码:
MyString& MyString::operator=(const MyString& str) { length = str.length; if (text) delete text; if (str.text == NULL) text = NULL; else { text = new char[length+1]; memcpy(text, str.text, length+1); } return *this; }
4
MyString::MyString(const char * cstr) {
length = strlen(cstr); text = new char[length+1]; memcpy(text, cstr, length+1); }
5
更完善的代码:
MyString::MyString(const char * cstr) { if (cstr==NULL || cstr[0]==0) { length = 0; text = NULL; } else { length = strlen(cstr); text = new char[length+1]; memcpy(text, cstr, length+1); } }
二、MyString类设计 #include &l { private: char * text; unsigned length; int compare(const MyString& str) { return strcmp(text, str.text); };
3
unsigned GetLength() { return length; } char * GetText() { return text; } };
MyString:: MyString() { text = NULL; length = 0; }
MyString:: ~MyString() { if (text != NULL) delete text; };
6
MyString::MyString(const MyString& str) { length = str.length;
text = new char[length+1]; memcpy(text, str.text, length+1); }
7
更完善的代码: MyString::MyString(const MyString& str) { length = str.length; if (str.text == NULL) text = NULL; else { text = new char[length+1]; memcpy(text, str.text, length+1); } }
1
public: MyString(); MyString(const MyString& str); MyString(const char * cstr); ~MyString() MyString& operator=(const MyString& str); friend MyString operator+(const MyString& str1, const MyString& str2);