类string的构造函数&析构函数&赋值函数

class String
{
public:
String(const char *str=NULL); //普通构造函数
String(const String &other);  //复制构造函数
~String();                     //析构函数
String & operator=(const String &other);// 赋值函数

private:
char *m_String;                //私有成员,保存字符串 ;
};

String::~String(void)
{
if(m_String!=NULL)
{
delete m_String;
m_String=NULL;

}
}

String::String(const char *str)
{
if(str==NULL)
{
m_String=new char[1];
*m_String='/0';
}
else
{
m_String=new char[strlen(str)+1];
strcpy(m_String,str);
}
}

String::String(const String &other)
{
m_String=new char[strlen(other.m_String)+1];
strcpy(m_String,other.m_String );
}

String & String::operator=(const String &other)
{
if(this==&other)
return *this;
delete[] m_String;
m_String=new char[strlen(other.m_String)+1];
strcpy(m_String,other.m_String);

return *this;

}


注:1、赋值函数是对一个已经初始化的对象进行operator=操作:class A;
                                                                                                      A a;
                                                                                                      A b;
                                                                                                      b=a; //赋值函数调用


             首先判断当前对象与引用传递对象是否是同一个对象,if yes,不做操作,直接返回;否则,先释放当前对象的堆内存,然后再分              配足够大小长度的堆内存复制对象;
    2、复制函数是一个对象初始化一块内存区域,即新对象的内存区:
class A;
                                                                                                           A a;
                                                                                                           A b=a;       //复制构造函数调用
                                                                                                           A  b(a); //复制构造函数调用
                  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章