免费注册 查看新帖 |

Chinaunix

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

[函数] 求助!关于默认构造函数!!在线等!! [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-09-04 17:14 |只看该作者 |正序浏览
#include <iostream.h>
#include <string.h>

class Student
{
public:
    Student(char *pName="no name",int ssId=0)
    {
        id=ssId;
        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;
    }
    ~Student()
    {
        cout<<"Destructing "<<name<<endl;
    }
protected:
    char name[40];
    int id;
};

class Tutor
{
public:
    Tutor(Student& s):student(s)
    {
        cout<<"Constructing tutor\n";
    }
protected:
    Student student;
};

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

void main()
{
    Student randy("Randy",1234);
    Tutor tutor(randy);
    cout<<"Calling fn()\n";
    fn(tutor);//这句不懂
    cout<<"Returned from fn()\n";
}

书上说到fn(tutor);这句时应该调用Tutor的默认拷贝构造函数,但用VC进行单步跟踪时发现程序执行到这句时是调用了STUDENT类的拷贝构造函数,不懂啊!!!!高手讲讲好吗??!!

[ 本帖最后由 czlt 于 2006-9-4 21:32 编辑 ]

论坛徽章:
0
17 [报告]
发表于 2006-09-04 22:28 |只看该作者
谢谢大家,我懂了!!

论坛徽章:
0
16 [报告]
发表于 2006-09-04 22:14 |只看该作者
fn(tutor) 会自动调用Tutor默认构造函数.并在Tutor调用默认拷贝构造函数过程中调用Student的拷贝构造函数以完成对成员变量student的拷贝

论坛徽章:
0
15 [报告]
发表于 2006-09-04 22:08 |只看该作者
我的代码意图很明显吧?
  1. Tutor(Tutor& s){cout<<"Tutor(Turtor& s)"<<endl;}
复制代码

既然默认的拷贝构造函数你看不到,那你就写一个自己拷贝构造函数,看看是否调用了。
去掉Tutor(Student& s):student(s)的初始化列表是为了避免调用Student的拷贝构造函数。

论坛徽章:
0
14 [报告]
发表于 2006-09-04 22:07 |只看该作者
可能是因为传值的原因吧
你换成引用看看

论坛徽章:
0
13 [报告]
发表于 2006-09-04 22:03 |只看该作者
和楼主的一样啊,否则有什么意义?
引用和指针会产成拷贝吗?

论坛徽章:
0
12 [报告]
发表于 2006-09-04 21:57 |只看该作者
不知playmud这样做要说明什么??

你确认你的代码能够编译吗?

具体调用哪个构造函数,取决与fn函数的原型,但你的代码根本没有给出来.

论坛徽章:
0
11 [报告]
发表于 2006-09-04 21:38 |只看该作者
不知playmud这样做要说明什么??

论坛徽章:
0
10 [报告]
发表于 2006-09-04 21:33 |只看该作者
抱歉!!忘加FN函数了,已经加上去了!!

论坛徽章:
0
9 [报告]
发表于 2006-09-04 19:21 |只看该作者
fn函数的原型是什么?
  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP