// 深拷贝和浅拷贝 // 深拷贝举例 #include #include #include using namespace std; class Person { private: char *name; int age; public: Person(const char *name, int age) { this->name = (char *)malloc(32); strcpy(this->name, name); this->age = age; } Person(const Person &obj) // 深拷贝,重写构造方法 { this->name = (char *)malloc(32); strcpy(this->name, obj.name); this->age = obj.age; } ~Person() { if (name != NULL) { free(name); } } public: void setName(char *name) { strcpy(this->name, name); } void show() { cout << this << " " << name << ", " << age << endl; } }; int main() { Person p1("disen", 20); Person p2 = p1; p2.setName("lucy"); Person p3 = Person(p2); p3.setName("Jack"); p1.show(); p2.show(); p3.show(); return 0; }