String类重写
#include <iostream> #include<string.h> using namespace std; class String { int length; int i; private: char* m_data;//用于保护字符串 public: String(const char *str=NULL)//普通构造函数 { cout<<"调用了构造函数"<<endl; if(str==NULL) { length=0; m_data=new char(1); //指针指向这段空间 m_data[0]='\0'; } else length=strlen(str); m_data=new char(length+1); strcpy(m_data, str); } String(const String &other)//拷贝构造函数 { cout<<"调用了拷贝函数"<<endl; if(m_data) { delete []m_data; int length=strlen(other.m_data); m_data=new char[length+1]; strcpy(m_data, other.m_data); } } ~String(void)//析构函数 { cout<<"调用了析构函数"<<endl; if (m_data) { delete []m_data; } } String &operator=(const String &other)//赋值函数 { cout<<"调用了赋值函数"<<endl; if (this==&other) //检查自赋值 return *this; delete []m_data; int length=strlen(other.m_data); m_data=new char[length+1]; strcpy(m_data, other.m_data); return *this; } }; int main() { String str("abc"); String str1(str); str.operator=(str); }