📄 demo_copy_constructor_1.cpp
字号:
//***************************************************
# include <iostream.h>
# include <string.h>
class Student
{
public:
Student(char* pName="no name",int sID=0) //构造函数
{
cout<<"Constructing new student "<<pName<<endl;
strcpy(name,pName);
id=sID;
}
Student(Student& s) //拷贝构造函数
{
cout<<"Constructing copy of "<<s.name<<endl;
strcpy(name,s.name);
id=s.id;
}
~Student() //析构函数
{
cout<<"Destructing "<<name<<endl;
}
protected:
char name[40];
int id;
};
void fn(Student s) //产生一个实参副本
//void fn(Student& s) //没有产生任何副本
{
cout<<" In function fn()"<<endl;
}
void main()
{
Student jenny("Jenny",1234);
cout<<" Calling fn()"<<endl;
fn(jenny); //实参jenny到形参s的拷贝构造
cout<<" Returned from fn()"<<endl;
}
/***1
Constructing new student Jenny
Calling fn()
Constructing copy of Jenny
In function fn()
Destructing Jenny
Returned from fn()
Destructing Jenny
/***2
Constructing new student Jenny
Calling fn()
In function fn()
Returned from fn()
Destructing Jenny
***/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -