1. #include<bits/stdc++.h>
    2. using namespace std;
    3. /**
    4. * 拷贝构造函数解决指针悬挂问题
    5. * */
    6. class Person {
    7. private:
    8. char *name;
    9. int age;
    10. public:
    11. Person(char *, int);
    12. Person(const Person &p); // 拷贝构造函数
    13. ~Person();
    14. void setAge(int);
    15. void print();
    16. };
    17. Person::Person(char *Name, int Age) {
    18. name = new char[strlen(Name)+1];
    19. strcpy(name, Name);
    20. age = Age;
    21. cout<<"construct"<<endl;
    22. }
    23. Person::~Person() {
    24. cout<<"destruct"<<endl;
    25. delete name;
    26. }
    27. Person::Person(const Person &p) {
    28. name = new char[strlen(p.name)+1];
    29. strcpy(name, p.name);
    30. age = p.age;
    31. cout<<"copy construct"<<endl;
    32. }
    33. void Person::setAge(int Age) {
    34. age = Age;
    35. }
    36. void Person::print() {
    37. printf("%s\t the address of name is %p\n", name, &name);
    38. }
    39. int main() {
    40. Person p1("console", 21);
    41. Person p2 = p1;
    42. p1.setAge(1);
    43. p2.setAge(2);
    44. p1.print();
    45. p2.print();
    46. return 0;
    47. }