#include<bits/stdc++.h>
using namespace std;
/**
* 拷贝构造函数解决指针悬挂问题
* */
class Person {
private:
char *name;
int age;
public:
Person(char *, int);
Person(const Person &p); // 拷贝构造函数
~Person();
void setAge(int);
void print();
};
Person::Person(char *Name, int Age) {
name = new char[strlen(Name)+1];
strcpy(name, Name);
age = Age;
cout<<"construct"<<endl;
}
Person::~Person() {
cout<<"destruct"<<endl;
delete name;
}
Person::Person(const Person &p) {
name = new char[strlen(p.name)+1];
strcpy(name, p.name);
age = p.age;
cout<<"copy construct"<<endl;
}
void Person::setAge(int Age) {
age = Age;
}
void Person::print() {
printf("%s\t the address of name is %p\n", name, &name);
}
int main() {
Person p1("console", 21);
Person p2 = p1;
p1.setAge(1);
p2.setAge(2);
p1.print();
p2.print();
return 0;
}