首页 > 编程语言 > 详细

C++ 浅拷贝与深拷贝

时间:2020-10-08 22:22:05      阅读:38      评论:0      收藏:0      [点我收藏+]
#include <iostream>
#include <string>


using namespace std;


class Student
{
public:
    Student() {
        cout << "默认构造函数" << endl;
    };
    Student(int a, int s)
    {
        cout << "有参构造函数" << endl;
        age = a;
        salary = new int(s);    // 这里
    }
    Student(const Student &s)
    {
        age = s.age;
        //salary = s.salary;  这里,浅拷贝就是直接赋值。 
        salary = new int(*s.salary);// 深拷贝是在堆上开辟新的空间。 这就是拷贝构造中,涉及到指针属性的深拷贝
        cout << "拷贝构造函数" << endl;
    }
    ~Student() {
        if (salary != NULL) {    // 这里
            delete salary;
            salary = NULL;
        }

        cout << "析构函数" << endl;
    }

    int age;
    int *salary;

};
int main() {

    Student s(22,6000);
    Student s1(s);

    cout << *s.salary << "  "<< *s1.salary << endl;
    return 0;

}

 

C++ 浅拷贝与深拷贝

原文:https://www.cnblogs.com/654321cc/p/13782646.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!