zoukankan      html  css  js  c++  java
  • C++ 浅拷贝与深拷贝

    #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;
    
    }
  • 相关阅读:
    一个自动化测试工具 UI Recorder
    通俗理解http2.0
    IE 问题集合
    webpack
    性能工具集合
    网络 问题
    css命名规范
    ajax 总结
    CSS深入理解学习笔记之relative
    jQuery插件开发通用框架
  • 原文地址:https://www.cnblogs.com/654321cc/p/13782646.html
Copyright © 2011-2022 走看看