#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;
//拷贝构造:拿已经定义过的有值的对象给新的对象初始化
//复制运算符=重载:定义过的两个对象,其中一个对象的值赋值给另一个对象
}
深拷贝与浅拷贝
深拷贝与浅拷贝:申请动态内存时才存在(new、delete)
在申请动态内存中,返回指向内存首地址的指针
浅拷贝:只拷贝指针的首地址,这两个对象最后指向的是同一块内存,两个指针指向同一块内存
深拷贝:自定义的拷贝方式,重新申请一块内存,把要拷贝的内存的内容放到申请的新的内存中,两个指针指向不同的内存