class String
{
public:
String( const char *str);
String( const String &other);
~String();
String &operator=(const String &other);
private:
char *data;
};
//构造函数
String::String(const char *str)
{
if (str == NULL) //指针可能为空,要判断
{
data = new char [1];
*data = '\0';
}
else
{
int length = strlen(str );
data = new char [length + 1];
strcpy(data, str);
}
}
//析构函数
String::~String()
{
delete data;
}
//拷贝构造函数
String::String(const String & other)
{
int length = strlen(other .data);
data = new char [length + 1];
strcpy(data, other.data);
}
//赋值函数
String &String ::operator=(const String & other)
{
if (this == &other) //引用不可能为空,所以不用判断,注意不要错写为:if(*this==other)
{
return *this ;
}
delete data; //释放原有的内存资源,以后没机会释放
int length = strlen(other .data); //strlen不包含‘0’,strcpy包含‘0’一起复制
data = new char [length + 1];
strcpy(data, other.data);
return *this ; //返回本对象的引用,为了实现像a=b=c这样的链式表达
}
时间问题,后期有需要补充的会陆续补充