Copy constructor, operator overloading, deep and shallow copying

#include<iostream>
#include<string.h>

using namespace std;

class Student{
public:
        Student(){m_strName="Jim";}
        /*
        默认的拷贝构造函数:
        Student(const Student &stu){}
        */
        Student(const Student &stu){
        m_strName=stu.m_strName;
    }
        //显性定义的拷贝构造函数

    //运算符重载
    friend istream & operator>>(istream & is,Student& stu);
    friend ostream & operator<<(ostream & os,Student& stu);
private:
        string m_strName;

};
istream & operator>>(istream & is,Student& stu){
    is>> stu.m_strName;
    return is;
}
ostream & operator<<(ostream & os,Student& stu){
    os<< stu.m_strName;
    return os;
}
int main()
{
    Student stu1;
    cout<<"请输入一个整数stu1"<<endl;
    cin>>stu1;
    cout<<endl;//把输入的字符串赋值给对象需要对输入输出运算符重载,C++对象的输入输出需要运算符重载
    Student stu2=stu1;
    Student stu3(stu1);
    cout<<"stu1="<<stu1<<","<<"stu2="<<stu2<<","<<"stu3="<<stu3<<endl;
    return 0;
    //拷贝构造:拿已经定义过的有值的对象给新的对象初始化
    //复制运算符=重载:定义过的两个对象,其中一个对象的值赋值给另一个对象
}

deep copy vs shallow copy

Deep copy and shallow copy: only exist when applying for dynamic memory (new, delete)
In applying for dynamic memory, a pointer to the first address of the memory is returned
Shallow is copied, and the two objects finally point to the same block Memory, two pointers point to the same piece of memory
Deep copy: a custom copy method, re-apply for a piece of memory, put the content of the memory to be copied into the new memory applied for, and the two pointers point to different memories

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325919074&siteId=291194637