构造函数-深拷贝与浅拷贝

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 //构造函数(拷贝构造函数),析构函数,
 5 /*深拷贝:是指编译器给类提供定默认拷贝构造函数拷贝含有指针成员对象时,
 6          调用默认析构函数多次释放堆中同一块内存,导致内存访问异常。
 7 
 8 解决办法:自定义拷贝构造函数,针对指针成员,
 9          用new关键字开辟另一块堆内存,存放拷贝对象的指针成员。
10 */
11 class Student
12 {
13 public:
14 
15     Student() {}
16     //默认析构函数
17     /*
18     Student( Student &stu)
19     {
20         m_age = stu.m_age;
21         p = stu.p;
22     }
23     */
24 
25     //自定义析构函数
26     Student(const Student &stu)
27     {
28         m_age = stu.m_age;
29         p = new int(*stu.p);
30     }
31 
32     void showStudent()
33     {
34         cout << m_age << endl;;
35         cout << *p << endl;
36         cout << "" << endl;
37     }
38 //private:
39     int m_age;
40     int *p;
41 
42 };
43 
44 int main()
45 {
46     int a = 6;
47     //Student s1(10,&a) 错误操作,自定义析构函数之后,编译器不再提供默认普通构造函数来初始化;
48     Student s1;
49     s1.m_age = 10;
50     s1.p = &a;
51 
52     Student s2=s1;
53     s1.showStudent();
54     s2.showStudent();
55 
56     system("pause");
57     return 0;
5//构造函数

猜你喜欢

转载自www.cnblogs.com/rtblogs/p/12001246.html