浅拷贝代码示例
#include<iostream>
#include<string>
using namespace std;
class Student {
public:
int m_age;
//构造函数传入年龄值
Student(int a) {
m_age = a;
}
};
int main() {
Student p1(18);
Student p2(p1);//利用默认拷贝构造函数实现浅拷贝
cout << "p1的年龄为: " << p1.m_age << endl;
cout << "p2的年龄为: " << p2.m_age << endl;
system("pause");
return 0;
}
此时完成了浅拷贝,将p1拷贝给了p2 ,下面我们添加一个指针成员变量身高,再次进行拷贝
#include<iostream>
#include<string>
using namespace std;
class Student {
public:
int m_age;
int* m_height;
//构造函数传入年龄值和身高值
Student(int a,int b) {
m_age = a;
m_height = new int(b);
//在堆区new一个地址来存放身高,用m_height接收
}
//我们在构造函数中使用new在堆区开辟了一个地址所以需要手动编写析构函数释放
~Student() {
delete m_height;
}
};
int main() {
Student p1(18,180);
Student p2(p1);
cout << "p1的年龄为: " << p1.m_age << " p1的身高为: " << *p1.m_height << endl;
cout << "p2的年龄为: " << p2.m_age << " p2的身高为: " << *p1.m_height << endl;
system("pause");
return 0;
}
此时系统崩溃,是由于浅拷贝两个对象的只进行了值传递,而身高共用一个地址,delete释放同一个地址两次导致崩溃,所以我们需要深拷贝,拷贝指针变量时新开辟地址。
#include<iostream>
#include<string>
using namespace std;
class Student {
public:
int m_age;
int* m_height;
//构造函数传入年龄值和身高值
Student(int a,int b) {
m_age = a;
m_height = new int(b);
//在堆区new一个地址来存放身高,用m_height接收
}
//我们在构造函数中使用new在堆区开辟了一个地址所以需要手动编写析构函数释放
~Student() {
delete m_height;
}
//深拷贝构造函数
Student(const Student& p) {
m_age = p.m_age;
//m_height = p.m_height;(默认浅拷贝构造函数,只拷贝值)
m_height = new int(*p.m_height);
}
};
int main() {
Student p1(18,180);
Student p2(p1);//用新的拷贝构造函数进行深拷贝
cout << "p1的年龄为: " << p1.m_age << " p1的身高为: " << *p1.m_height << endl;
cout << "p2的年龄为: " << p2.m_age << " p2的身高为: " << *p1.m_height << endl;
system("pause");
return 0;
}
ok,程序运行成功,没有报错!