string类中使用到了赋值构造函数、复制构造函数、构造函数、默认构造函数、析构函数、重载操作符等一些类操作
class String { public: String() { data = new char; data[0]='\0'; length = 0; } String(const char* str) { length = strlen(str); data = new char[length+1]; strcpy(data,str); data[length]='\0'; } String(const char* str,int n) { length = n; data = new char[n+1]; strncpy(data,str,n); data[length] ='\0'; } String(const String& src) { length = src.length; data = new char[length+1]; strcpy(data,src.data); } String& operator=(const String& src) { if(this == &src) return *this; delete [] data; data = new char[src.length+1]; strcpy(data,src.data); return *this; } String& operator=(const char* src) { delete [] data; length = strlen(src); data = new char[length+1]; strcpy(data,src); return *this; } char& operator[](int n) { return data[n]; } const char& operator[](int n) const { return str[n]; } ostream& operator<<(ostream& os,const string& st) { os<<st.data<<endl; return os; } ~String() { delete [] data; } private: char* data; int length; };
时间: 2024-10-06 00:40:54