请帮我解释一下这个默认拷贝构造函数!
ztwz 2004-09-25 04:18:57 我看的书是钱能的c++程序设计,看到默认拷贝构造函数这儿十在是晕得很,请大题帮我解惑!问题我都用注释写在代码相应位置了!谢谢
#include <iostream>
#include <string.h>
using namespace std;
class student
{
public:
student(char *pname="no name")
{
cout<<"1 新建一个类"<<pname<<endl;
strcpy(name,pname);
name[sizeof(name)-1]='\0';
}
student(student& s)
{
cout<<"2 拷贝类"<<s.name<<endl;
strcpy(name,"copy of");
strcat(name,s.name);
}
~student()
{
cout<<"3 消毁类"<<name<<endl;
}
protected:
char name[40];
};
class tutor
{
public:
tutor(student& s):student(s)
{
cout<<"4 建立tutor类\n";
}
protected:
student student;/*这儿这东东为什么在dev c++里编译出错 declaration of `student tutor::student我在vs.net里就没问题*/
};
void fn(tutor tutor)//函数执行到这儿的时候就构造tutor,而tutor又要复制student呀怎么没复制?
{
cout<<"5 在函数fn()中\n";
}
int main()
{
student randy("randy");
tutor tutor(randy);
cout<<"6 调用fn()\n";
fn(tutor);
cout<<"7 返回fn()\n";
}
这是运行后的结果:
1 新建一个类randy
2 拷贝类randy
4 建立tutor类
6 调用fn()
2 拷贝类copy ofrandy
5 在函数fn()中
3 消毁类copy ofcopy ofrandy
7 返回fn()
3 消毁类copy ofrandy
3 消毁类randy
按我的理解应该执行结果是这样的:
1 新建一个类randy
2 拷贝类randy
4 建立tutor类
6 调用fn()
2 拷贝类copy ofrandy
4 建立tutor类 //我的问题也就是多了这一步
5 在函数fn()中
3 消毁类copy ofcopy ofrandy
7 返回fn()
3 消毁类copy ofrandy
3 消毁类randy