题解 | #浅拷贝和深拷贝#
浅拷贝和深拷贝
https://www.nowcoder.com/practice/535753110cbd4e8987adc2e67f392ab7
#include <iostream> #include <cstring> #pragma warning(disable : 4996) //忽视4996类警告问题 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; } // 给 Person 添加一个拷贝构造函数 Person (const Person &p){ //拷贝构造函数参数通常使用const 引用 this->name = new char[strlen(p.name)+1]; strcpy (this->name,p.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构造函数 Person p2 = p1; //深拷贝,建立p2对象 p2.showPerson(); return 0; }#我的求职思考##你的秋招进展怎么样了##零基础学习C++#