operator= 和 拷贝构造 区别?
相同点: 默认的是浅拷贝
不同点: 拷贝构造 是对象创建初始化的时候执行,
operator=是对象创建完,重新=号赋值
#include<iostream>
#include <list>
using namespace std;
/*operator= 和 拷贝构造 区别?
相同点: 默认的是浅拷贝
不同点: 拷贝构造 是对象创建初始化的时候执行,
operator=是对象创建完,重新=号赋值*/
class CPerson
{
public:
int *m_a;
public:
CPerson()
{
m_a = new int(10);
}
~CPerson()
{
delete m_a;
m_a = 0;
}
//public:
// CPerson& operator=(const CPerson& ps) // 浅拷贝
// {
// this->m_a = ps.m_a;
// return *this;
// }
// CPerson& operator=(const CPerson& ps) // 深拷贝
// {
// // 删除原有的空间
// delete this->m_a;
// // 重新分配
// this->m_a = new int;
// *(this->m_a) = *(ps.m_a);
// return *this;
// }
};
int main()
{
/*CPerson aa;
CPerson bb;
bb = aa;*/
//CPerson aa;
//CPerson bb;
//list<CPerson*> ps;
//ps.push_back(&aa);
//ps.push_back(&bb);
system("pause");
return 0;
}