一、浅拷贝
#include <iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
class Person
{
private:
char *m_name;
int m_num;
public:
Person()
{
m_name = NULL;
m_num = 0;
cout << "已调用无参构造..." << endl;
}
Person(char *name,int num)
{
m_name = (char *)calloc(1,strlen(name)+1);
if(m_name == NULL)
{
cout<<"构造失败"<<endl;
}
cout<<"-->已经申请好空间"<<endl;
strcpy(m_name,name);
m_num = num;
cout<<"已调用有参构造..."<<endl;
}
~Person()
{
if(m_name != NULL)
{
cout<<"m_name的空间已被释放"<<endl;
free(m_name);
m_name = NULL;
}
cout<<"析构函数调用结束..."<<endl;
}
void showPerson()
{
cout << "m_name = " << m_name << ", m_num = " << m_num << endl;
}
};
void demo1()
{
Person p1("Chung", 42607);
p1.showPerson();
Person p2= p1;
}
void demo2()
{
Person p3;
p3.showPerson();
Person p4= p3;
p4.showPerson();
}
int main(int argc, char *argv[])
{
demo1();
return 0;
}

二、深拷贝
#include <iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
class Person
{
private:
char *m_name;
int m_num;
public:
Person()
{
m_name = NULL;
m_num = 0;
cout << "已调用无参构造..." << endl;
}
Person(char *name,int num)
{
m_name = (char *)calloc(1,strlen(name)+1);
if(m_name == NULL)
{
cout<<"构造失败"<<endl;
}
cout<<"-->已经申请好空间"<<endl;
strcpy(m_name,name);
m_num = num;
cout<<"已调用有参构造..."<<endl;
}
Person(const Person &p)
{
cout << "--------------------拷贝构造函数----------------------" << endl;
m_name= (char *)calloc(1, strlen(p.m_name)+1);
cout << "空间已被申请" << endl;
strcpy(m_name, p.m_name);
m_num= p.m_num;
cout << "--------------------拷贝构造函数----------------------" << endl;
}
~Person()
{
if(m_name != NULL)
{
cout<<"m_name的空间已被释放"<<endl;
free(m_name);
m_name = NULL;
}
cout<<"析构函数调用结束..."<<endl;
}
void showPerson()
{
cout << "m_name = " << m_name << ", m_num = " << m_num << endl;
}
};
void demo1()
{
Person p1("Chung", 42607);
p1.showPerson();
Person p2= p1;
}
void demo2()
{
Person p3;
Person p4= p3;
p4.showPerson();
}
int main(int argc, char *argv[])
{
demo2();
return 0;
}
