您的位置:首页 > 其它

编写string类的构造、拷贝构造、析构、拷贝赋值函数

2018-03-14 12:06 218 查看
内容会持续更新,有错误的地方欢迎指正,谢谢!

#include<iostream>
using namespace std;
class String
{
public:
String(const char *str=NULL);            //构造函数
String(const String &other);             //拷贝构造函数
~String(void);                           //析构函数
String & operator=(const String &other); //拷贝赋值函数
private:
char *m_String;                          //私有成员,保存字符串
};
String::String(const char *str)
{
cout<<"普通构造函数"<<endl;
if(str==NULL)                         //如果str为空,存空字符串
{
m_String=new char[1];             //分配一个字节
*m_String='\0';                   //将之赋值为字符串结束符
}
else
{
m_String=new char[strlen(str)+1]; //分配空间容纳str内容
strcpy(m_String,str);             //赋值str到私有成员
}
}
String::String(const String &other)
{
cout<<"拷贝构造函数"<<endl;
m_String=new char[strlen(other.m_String)+1];
strcpy(m_String,other.m_String);
}
String::~String(void)
{
cout<<"析构函数"<<endl;
if(m_String!=NULL)                    //如果m_String 不为NULL,释放堆内存
{
delete[] m_String;                //释放后置为NULL
m_String=NULL;
}
}
String& String::operator =(const String &other)
{
cout<<"拷贝赋值函数"<<endl;
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;
}
int main()
{
String a("hello");           //调用普通构造函数
String b("word");            //调用普通构造函数
String c(a);                 //调用拷贝构造函数
c=b;                         //调用拷贝赋值函数
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string