C++浅拷贝与深拷贝
通俗易懂,就是被复制的和复制的是同一片地址,而深拷贝的话是两个不同的地址
深拷贝与浅拷贝:c++不知道,你用一把钥匙来构造另一把钥匙的目的是什么
最朴素的复制一把一模一样的钥匙
两把钥匙指向同一空间
#include <iostream>
#include <cstring>
using namespace std;
class Student
{
char *name;
char sex;
int id;
public:
Student()
{
cout<<"默认构造"<<endl;
}
Student(const char *name=" ", char sex=0, int id=0)
{
int len = strlen(name);
this->name = new char[len+1];
strcpy(this->name, name);
this->sex = sex;
this->id = id;
cout<<"构造"<<endl;
}
Student(const Student& that)
{
name=that.name; //两个name使用的是同一块地址
sex=that.sex;
id=that.id; //默认拷贝构造
cout<< &that.name<<" "<<&name<<endl;
/*
int len=strlen(that.name);
this->name=new char[len+1];
strcpy(this->name, that.name);
this->sex=that.sex;
this->id=that.id; //深拷贝(开辟内存
cout<< &that.name<<" "<<&name<<endl;
cout<<"拷贝构造"<<endl; //为了s1和s2不共用一块内存*/
}
~Student()
{
delete[] name;
cout<<"析构"<<endl;
}
Student& operator=(const Student& that)
{
if(this!=&that) //防止自拷贝
{
delete[] name;
int len=strlen(that.name);
name=new char[len+1];
strcpy(name, that.name);
sex=that.sex;
id=that.id;
}
cout<<"赋值"<<endl;
return *this;
}
void show(void)
{
cout<<&name<<" "<<name<<endl;
}
};
//没有开辟空间,会重复释放空间,导致段错误
int main()
{
Student s1("ke19",'m',1001);
Student s2(s1);
// Student s3 ;
//s3=s1;
s1.show();
s2.show();
}
原文地址:https://blog.csdn.net/m0_67677309/article/details/143477825
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!