请教这段程序在哪块调用拷贝构造函数的
请问这段程序在哪块调用拷贝构造函数的
#include<iostream.h>
#include<string.h>
class Student
{
public:
Student(char *pName="no name",int ssId=0)
{
strcpy(name,pName);
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;
cout<<"拷贝构造函数"<<endl;
}
~Student()
{
cout<<"Destructing"<<name<<endl;
}
protected:
char name[40];
int id;
};
void fn(Student s)
{
cout<<"In function fn()\n";
}
void main()
{
Student randy("Randy",1234);
cout<<"Calling fn()\n";
fn(randy);
cout<<"Retruned from fn()\n";
}
------解决方案--------------------
#include<iostream.h>
#include<string.h>
class Student
{
public:
Student(char *pName="no name",int ssId=0)
{
strcpy(name,pName);
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;
cout<<"拷贝构造函数"<<endl;
}
~Student()
{
cout<<"Destructing"<<name<<endl;
}
protected:
char name[40];
int id;
};
void fn(Student s)
{
cout<<"In function fn()\n";
}
void main()
{
Student randy("Randy",1234);
cout<<"Calling fn()\n";
fn(randy);
cout<<"Retruned from fn()\n";
}
------解决方案--------------------
- C/C++ code
void main() { Student randy("Randy",1234); cout<<"Calling fn()\n"; fn(randy); // 传递形参的时候要复制randy 调用拷贝构造函数! cout<<"Retruned from fn()\n"; }