深拷贝与浅拷贝
- 浅拷贝
简单运算操作,类似于赋值操作
class Person{
public:
Person(const Person & p){
m_a,ge=p.age;//这一步便为浅拷贝操作
}
public:
int m_age;
}
- 深拷贝
在堆区重新申请内存空间,进行拷贝操作
class Person{
public:
//无参构造函数
Person(){
cout<<"无参构造函数启动!"<<endl;
}
//有参构造函数
Person(int age,int height){
cout<<"有参构造函数启动!"<<endl;
m_Age=age;
m_Height=new int(height);
}
//拷贝构造函数
Person(const Person & p){
cout<<"拷贝构造函数启动!"<<endl;
m_Age=p.m_Age;
//在堆区重新申请内存,避免因为浅拷贝带来的内存重复释放的问题
m_Height=new int(*p.m_Height);
}
//析构函数 释放局部变量 栈区上的内存
~Person(){
cout<<"析构函数启动!"<<endl;
if(!m_Height){
delete(m_Height);
}
}
public:
int m_Age;
int * m_Height;
};
void test(){
Person p(10,10);
Person p2(p);
cout<<"age="<<p2.m_Age<<endl<<"height="<<*p2.m_Height<<endl;
}
int main(){
test();
return 0;
}
初始化列表
在写有参构造函数的时候,我们往往需要详细写其变量的赋值操作,利用初始化列表可以进行快速的赋值操作
语法:构造函数():属性1(值1),属性2(值2)... {}
//传统写法
Person(int age,int height){
m_Age=age;
m_Height=height;
}
//初始化列表
Person(int age,int height):m_Age(age),m_Height(height){};