拷贝构造函数举例
代码:
#include <iostream>
#include <cstring>
using namespace std;
class Student{
public:
Student(char* pName="no name",int ssId=0)
{
strncpy(name,pName,40);
name[39]='\0';
id = ssId;
cout <<"Constructing new student " <<pName <<endl;
}
Student(Student& s)
{
cout<<"Constructing copy of "<<s.name<<endl;
strcpy(name,"copy of ");
strcat(name,s.name);
id=s.id;
}
void show(){
cout<<"name="<<name<<" ,id="<<id<<endl;
}
~Student(){
cout <<"Destructing " <<name <<endl;
}
protected:
char name[40];
int id;
};
void fn(Student s)
{
cout <<"into function fn()\n";
s.show();
cout<<"out of function fn()\n";
}
int main()
{
Student randy("Randy",1234);
Student elizabeth=randy;
elizabeth.show();
cout <<"Calling fn()\n";
fn(randy);
cout <<"Returned from fn()\n";
}
编译运行结果:
Constructing new student Randy
Constructing copy of Randy
name=copy of Randy ,id=1234
Calling fn()
Constructing copy of Randy
into function fn()
name=copy of Randy ,id=1234
out of function fn()
Destructing copy of Randy
Returned from fn()
Destructing copy of Randy
Destructing Randy
本文通过一个具体的示例,详细介绍了C++中拷贝构造函数的实现方式及其工作原理。示例展示了当创建一个对象的副本时,拷贝构造函数如何被调用,并解释了在函数参数传递过程中拷贝构造函数的作用。
3032

被折叠的 条评论
为什么被折叠?



