自实现部分string类的功能
#define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; class MyString { public: MyString::MyString(); //无参构造 MyString(const char* str ); //默认参数 MyString(const MyString& other); //拷贝构造 MyString& operator=(const MyString& other); //重载等号(参数不同) MyString& operator=(const char* str); //重载等号(参数不同) ~MyString(); //析构函数 char& operator[](unsigned int index); //重载[]号 MyString& operator+=(const MyString& other); //重载+=号 friend MyString operator+(const MyString& s1, const MyString& s2); //重载加号;用全局的友元函数 friend ostream& operator<<(ostream& os, const MyString& str); //重载左移操作符;用全局函数
friend istream& operator>>(istream& is, MyString& str); //重载右移操作符,用全局函数 private: char* m_str; }; MyString::MyString() { m_str = new char[1]; m_str = '\0'; } MyString::MyString(const char* str) //默认参数 { if (str == NULL) { m_str = new char[1]; m_str = '\0'; } else { int len = strlen(str); m_str = new char[len + 1]; strcpy(m_str, str); } } MyString::MyString(const MyString& other) { int len = strlen(other.m_str); m_str = new char[len + 1]; strcpy(m_str, other.m_str); } MyString& MyString::operator=(const MyString& other) { if (&other == this) return *this; if (m_str != NULL) { delete[]m_str; } int len = strlen(other.m_str); m_str = new char[len + 1]; strcpy(m_str, other.m_str); return *this; } MyString& MyString::operator=(const char* str) { if (m_str != NULL) { delete[]m_str; } if (str == NULL) { m_str = new char[1]; m_str = '\0'; } else { int len = strlen(str); m_str = new char[len + 1]; strcpy(m_str, str); } return *this; } MyString::~MyString() { if (m_str != NULL) { delete[]m_str; m_str = NULL; } } char& MyString::operator[](unsigned int index) { unsigned int len = strlen(m_str); if (index > len) return m_str[len]; return m_str[index]; } MyString& MyString::operator+=(const MyString& other) { int len = strlen(m_str) + strlen(other.m_str); char *newstr = new char[len + 1]; strcpy(newstr, m_str); strcat(newstr, other.m_str); if (m_str != NULL) { delete[]m_str; } m_str = newstr; return *this; } MyString operator+(const MyString& s1, const MyString& s2) { int len = strlen(s1.m_str) + strlen(s2.m_str); char *newstr = new char[len + 1]; strcpy(newstr, s1.m_str); strcat(newstr, s2.m_str); MyString My(newstr); return My; } ostream& operator<<(ostream& os, const MyString& str) { os << str.m_str << endl; return os; } istream& operator>>(istream& is, MyString& str) { char newstr[1024]; is >> newstr; int len = strlen(newstr); if (str.m_str != NULL) { delete []str.m_str; } str.m_str = new char[len + 1]; strcpy(str.m_str, newstr); return is; } //测试代码 void test11() { MyString m1; MyString m2("nihao"); MyString m3(m2); cout << m2; cout << m3; m1 = m2 + m3; cout << m1; m1 += m3; cout << m1[-10] << endl; cin >> m3; cout << m3; } int main() { test11(); system("pause"); return EXIT_SUCCESS; }
路之遥