1 #include<iostream> 2 #include<cstring> 3 4 class String 5 { 6 public: 7 String(); 8 String(const char *str); 9 String(const String &rhs); 10 ~String(); 11 12 String &operator=(const String &rhs); 13 String operator+(const String &rhs); 14 char operator[](const unsigned int index); 15 bool operator==(const String &rhs); 16 friend std::ostream &operator<<(std::ostream &out, const String &rhs); 17 private: 18 char *m_data; 19 }; 20 21 String::String() 22 { 23 std::cout << "default constructor" << std::endl; 24 m_data = new char[1]; 25 m_data[0] = '\0'; 26 } 27 28 String::String(const char *str) 29 { 30 std::cout << "non-default constructor" << std::endl; 31 if (NULL == str) 32 { 33 m_data = new char[1]; 34 m_data[0] = '\0'; 35 } 36 else 37 { 38 m_data = new char[strlen(str)+1]; 39 strcpy(m_data, str); 40 } 41 } 42 43 String::String(const String &another) 44 { 45 std::cout << "copy constructor" << std::endl; 46 m_data = new char[strlen(another.m_data)+1]; 47 strcpy(m_data, another.m_data); 48 } 49 50 bool String::operator==(const String &rhs) 51 { 52 std::cout << "bool == " << std::endl; 53 int result = strcmp(m_data, rhs.m_data); 54 if (0 == result) 55 return true; 56 else 57 return false; 58 } 59 60 String &String::operator=(const String &rhs) 61 { 62 std::cout << "assign constructor" << std::endl; 63 if (this == &rhs) 64 return *this; 65 delete []m_data; 66 m_data = new char[strlen(rhs.m_data)+1]; 67 strcpy(m_data, rhs.m_data); 68 return *this; 69 } 70 71 String String::operator+(const String &rhs) 72 { 73 std::cout << "+" << std::endl; 74 String newString; 75 if (NULL == rhs.m_data) 76 newString = *this; 77 else if(NULL == m_data) 78 newString = rhs; 79 else 80 { 81 newString.m_data = new char[strlen(rhs.m_data)+strlen(m_data)+1]; 82 strcpy(newString.m_data, m_data); 83 strcat(newString.m_data, rhs.m_data); 84 } 85 return newString; 86 } 87 88 char String::operator[](const unsigned int index) 89 { 90 std::cout << "[]" << std::endl; 91 return m_data[index]; 92 } 93 94 std::ostream &operator<<(std::ostream &out, const String &rhs) 95 { 96 out << rhs.m_data; 97 return out; 98 } 99 100 String::~String() 101 { 102 std::cout << "destructor" << std::endl; 103 delete []m_data; 104 } 105 106 int main(void) 107 { 108 const char *p = "hello, world"; 109 String s = "hello, world"; // 构造函数隐式转换 调用非默认构造函数 110 String s1(p); // 调用非默认构造函数 111 String s2 = s1; // 调用非默认构造函数 112 String s3; // 调用默认构造函数 113 s3 = s1; // 调用赋值构造函数 114 String s4 = s3 + s1; // 调用+运算符,同时调用默认构造函数 115 bool flag(s1 == s2); // 调用==运算符 116 std::cout << s << std::endl; 117 std::cout << s1 << std::endl; 118 std::cout << s2 << std::endl; 119 std::cout << s3 << std::endl; 120 std::cout << flag << std::endl; 121 char result = s3[1]; // 调用[]运算符 122 std::cout << result << std::endl; 123 std::cout << s4 << std::endl; 124 125 return 0; 126 }