//1.
//对象拷贝的2种形式:
//(1) 类名 对象2(对象1); //people per1(per);
//(2) 类名 对象2 = 对象1 ; //people per1 = per;
//2.
//所以在对“含有指针成员的对象”进行拷贝时,必须要【自己定义拷贝构造函数】,
//使拷贝构造后的对象指针成员有自己的内存空间,即进行【深拷贝】,避免内存泄漏。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class people
{
public:
people(const char* nam, int a)
{
this->name = new char[strlen(nam) + 1];
strcpy(name, nam);
this->age = a;
}
#if 0
// 浅拷贝(就是拷贝构造函数)
// 实际上,拷贝构造函数由编译系统自动完成,不必用户去显示地调用,也不用显示地定义。
people(people& peo)
{
this->name = peo.name;
this->age = peo.age;
}
#endif
#if 1
// 深拷贝
people(people& peo)
{
this->name = new char[strlen(peo.name) + 1];
strcpy(this->name, peo.name);
this->age = peo.age;
}
#endif
~people()
{
cout << "~people:" << (int)name << endl;;
delete[] name;
}
void show()
{
cout << name << " " << age << endl;
}
///
/// \brief get_ad
/// \param p
/// 打印相关地址
void get_ad(people& p)
{
cout << "对象本身地址:" << (int)&p << endl;
cout << "&age:" << (int)&p.age << endl;
cout << "&name:" << (int)p.name << endl;
}
private:
char* name;
int age;
};
int main()
{
people per("zhang", 19);
people per1(per);
cout << "【per】中的地址成员地址:" << endl;
per.get_ad(per); cout << endl;
cout << "【per1】中的地址成员地址:" << endl;
per1.get_ad(per1); cout << endl;
return 0;
}
使用深拷贝:程序运行正常。
使用浅拷贝,程序运行崩溃。