C++类中的特殊函数
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| class String{ private: char* str; int len; public: String () { len = 0; str = nullptr; }
String (const char* s) { len = std::strlen(s); str = new char[len + 1]; std::strcpy(str, s); }
String (const String& st) { len = st.len; str = new char[len + 1]; std::strcpy(str, st.str); } String (String&& st) noexcept { len = st.len; str = st.str; st.str = nullptr; st.len = 0; }
String& operator= (const String& st) { if (this == &st) return *this; delete[] str; len = st.len; str = new char[len + 1]; std::strcpy(str, st.str); return *this; } String& operator= (String&& st) noexcept { if (this == &st) return *this; delete[] str; len = st.len; str = st.str; st.str = nullptr; st.len = 0; return *this; }
char& operator[] (int i) { return str[i]; } const char& operator[] (int i) const{ return str[i]; }
friend ostream& operator<< (ostream& os, const String& st) { os << st.str; return os; }
~String() { delete[] str; len = 0; } };
|
参考
- 《C++ Primer Plus 中文版》 chapter 12