浅拷贝和深拷贝实现

#include <bits/stdc++.h>
using namespace std;

class student {
private:
    char* name;
public:
    student() {
        name = new char(20);
        cout << "创建student" << endl;
    };
    ~student() {
        cout << "删除student " << name << endl;
        delete name;
    }
    student(const student& s) {
        //浅拷贝
        //name = s.name;
        //深拷贝
        name = new char(20);
        memcpy(name, s.name, strlen(s.name));
        cout << "深拷贝" << endl;
    }
};

int main()
{
    {
        student s1;
        student s2(s1);
    } //局部变量,结束则释放
    system("pause");

    return 0;
}

 

posted @ 2023-09-07 14:00  SuperTonyy  阅读(20)  评论(0)    收藏  举报