2020-06-11【拷贝构造的一个例子】注释

class CStudent
{
int sno;
public:
CStudent(int sno):sno(sno) {cout<<"\nCScon1:" ;}
CStudent():sno(0){cout<<"\nCScon2:";}
CStudent(CStudent& stu){ cout<<"\nCScon3:";sno=stu.sno+1;}
void display(){cout<<"\ndisp1:"<<sno;}
void display(CStudent s){cout<<"\ndisp2:"<<s.sno;}//传参的时候 s=stu1 发生拷贝构造(浅拷贝)
~CStudent(){}
};
void testCStu(){
cout<<"\nfun:testCStu"<<endl;
CStudent stu1(1);// stu1.sno = 1
stu1.display(stu1);//stu1传给了临时对象即形参s, 同时调用了构造函数CScon3,s.sno=sut1.sno+1=2
stu1.display();//但stu1 的原值没有变化
cout<<"\n--";
CStudent stu2=stu1;//建立新对象时调用了拷贝构造
stu2.display();
stu2=stu1;//并么有拷贝构造?不奇怪,并没有建立新的对象,不再调用构造函数,包括拷贝,只能赋值
stu2.display();
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。