题解 | #浅拷贝和深拷贝#
浅拷贝和深拷贝
https://www.nowcoder.com/practice/535753110cbd4e8987adc2e67f392ab7
#include <iostream>
#include <cstring>
using namespace std;
class Person {
public:
char* name; // 姓名
int age; // 年龄
// 浅拷贝:简单的赋值拷贝操作
// 深拷贝:在堆区重新申请空间,进行拷贝操作
Person(const char* name, int age) {
this->name = new char[strlen(name) + 1]; // 深拷贝,使用堆区
strcpy(this->name, name);
this->age = age;
}
// write your code here......
Person(const Person& p) { //拷贝构造函数
this->name = new char[strlen(p.name) + 1]; //设置name字符数组的长度
strcpy(this->name, p.name); //拷贝name数组
this->age = p.age;
}
void showPerson() {
cout << name << " " << age << endl;
}
~Person() {
if (name != nullptr) {
delete[] name; // 释放
name = nullptr;
}
}
};
int main() {
char name[100] = { 0 };
int age;
cin >> name;
cin >> age;
Person p1(name, age);
Person p2 = p1;
p2.showPerson();
return 0;
}

