主要是通过这个例子,理解拷贝构造函数和赋值函数的区别:
代码:

#include <iostream>
#include <string.h>
using namespace std;
class String
{
public:
//构造函数
String(char *str);
//拷贝构造函数
String(const String& other);
//赋值构造函数
String& operator=(const String& other);
//析构函数
~String();
private:
char *m_str=NULL; //保存字符串
};
//构造函数的实现
String::String(char *str)
{
cout<<"构造函数"<<endl;
//如果初始化时没有进行赋值
if(str==NULL)
{
//分配内存
m_str=new char[1];
//字符串加上结束符
m_str[0]='\0';
}
else{
//+1是由于还有个结束符\0
m_str=new char[strlen(str)+1];
strcpy(m_str,str);
}

}
//拷贝构造函数
String::String(const String &other)
{
cout<<"调用拷贝构造函数"<<endl;
m_str=new char(strlen(other.m_str)+1);
strcpy(m_str,other.m_str);
}
//赋值函数
String& String::operator=(const String& other)
{
cout<<"调用赋值函数"<<endl;
//先删除原理的数据
if(m_str!=NULL)
{
delete []m_str;
}
m_str=new char[strlen(other.m_str)+1];
strcpy(m_str,other.m_str);
//返回this的值
return *this;

}
//析构函数
String::~String()
{
cout<<"调用析构函数"<<endl;
if(m_str!=NULL)
{
delete []m_str;
m_str=NULL;
}
}
int main()
{

String a("sda");
//调用拷贝构造函数
String b(a);
//调用赋值构造函数
String c("Sda");
c=b;
return 0;
}