• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Striving_Life
博客园    首页    新随笔    联系   管理    订阅  订阅

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

 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//构造函数
posted @ 2019-12-07 11:58  Striving_Life  阅读(297)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3