拷贝构造函数的深拷贝和浅拷贝

如果类中的某个属性是指针,且该指针指向的是一个堆

当创建一个新的类,而且拷贝构造函数默认时或者是直接的赋值,那两个类的该属性就指向同一个地址,当在析构函数中加入删除堆的操作时,会报错

#include<iostream>
#include<string>
using namespace std;
class Student
{
private:
    int age;
    int *height;
public:
    Student(const Student &a){
        age = a.age;
        height = a.height; //这里就是一个简单的浅复制
    }
    Student(int age1, int height1){
        age = age1;
        height = new int(height1);
    }
    void printAge(){
        cout<<*height<<endl;
    }
    ~Student(){
        delete height;
        height = NULL;
        cout<<"我是析构函数"<<endl;
    }
};
int main(){
    system("chcp 65001");
    Student stu1(12, 135);
    Student stu2(stu1);
    stu2.printAge();
    system("pause");
    return 0;
}

解决方法就是在拷贝函数时,让height的指向开一个新的堆来保存

posted @ 2020-09-24 22:21  磊神加特林  阅读(158)  评论(0)    收藏  举报