摘自高质量C++编程指南
class String
{
public:
String(const char*str=NULL); //普通构造函数
String(const String &other); //拷贝构造函数
~String(void); //析构函数
String & operate = (const String &other); //赋值函数
private:
char *m_data; //字符串
};
String::~String(void)
{
delete [] m_data;
}
String::String(const char *str) //构造函数是一种特殊的类成员函数,是当创建一个类的对象时,它被调用来对类的数据成员进行初始化和分配内存
{
if(str==NULL)
{
m_data=new char [1];
*mdata='\0';
}
else
{
int length=strlen(str);
m_data=new char[length+1]; //不算'\0'
strcpy(m_data,str);
}
}
String::String(const String &other) //拷贝构造函数是C++独有的,它是一种特殊的构造函数,用基于同一类的一个对象构造和初始化另一个对象。
{
int length=strlen(other.m_data);
m_data=new char[length+1];
strcpy(m_data,other.m_data);
}
String &String::operate =(const String &other) //当一个类的对象向该类的另一个对象赋值时,就会用到该类的赋值函数。
{
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;
}