demo_copy_constructor_1.cpp

来自「对于一个初涉VC++的人来书」· C++ 代码 · 共 67 行

CPP
67
字号

//***************************************************

# 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 + =
减小字号Ctrl + -
显示快捷键?