免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1024 | 回复: 2
打印 上一主题 下一主题

[函数] 关于拷贝构造函数问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2004-09-22 13:03 |只看该作者 |倒序浏览
我在书上看了一段代码,对程序运行结果有点疑惑,请高手帮忙分析一下:
#include <iostream.h>;
#include <string.h>;

class Student
{
    public:
        student(char * pName="no name"
        {
            cout<<Constructing new student"<<pName<<endl;
            strcpy(name,pName);
            name[sizeof(name)-1]='\0';
         }
       Student(Student &s)
         {
             cout<<"Constructing copy of"<<s.name<<endl;
             strcpy(name,"copy of";
             strcat(name,s.name);
         }
         ~Student()
         {cout<<"Destructing"<<name<<endl;}
    protected:
              char name[40];
};
class Tutor
{
    public:
           Tutor(Student & s):student(s)
            {      cout<<"Constructing tutor\n";}
    protected:
           Student student;
};

void fn(Tutor tutor)
{      cout<<"In function fn()\n";}

woid main()
{
           Student randy("Randy";
           Tutor tutor(randy);
           cout<<"Calling fn()\n";
           fn(tutor);
           cout<<"Returned from fn()\n";
}


运行结果:
Constructing new student Randy
Constructing copy of Randy
Constructing tutor
Calling fn()
Constructing copy of copy of Randy
In function fn()
Destructing copy of copy of Randy
Returned from fn()
Destructing copy of Randy
Destructing Randy

我对第五行、第七行、第九行、第十行的输出结果有些疑惑。为什么有的有两个copy of  有的只有一个,有的没有?拜托各位前辈指导。谢谢。

论坛徽章:
1
荣誉版主
日期:2011-11-23 16:44:17
2 [报告]
发表于 2004-09-22 21:31 |只看该作者

关于拷贝构造函数问题

>;>;Tutor tutor(randy);
当执行上面这一句时,会执行下面这个。
>;>;Tutor(Student & s):student(s)
这样就执行了
》》student(s)
于是执行了
》》Student(Student &s)
现在你明白第五行的输出了吧?
至于第7,9,10行,构造函数和析构函数总是成对出现的,
这个很好理解吧?
推荐一本书
http://www.china-pub.com/computers/common/info.asp?id=3564

对了,你看看你的sizeof(name)是多少。
还有现在都这样用,你的那种用法已经不推荐了。

  1. #include <iostream>;
  2. #include <string>;
  3. using namespace std;
复制代码


以后贴代码用code功能。

论坛徽章:
0
3 [报告]
发表于 2004-09-24 15:24 |只看该作者

关于拷贝构造函数问题

谢谢指导
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP