}
};
主函数源文件为Li1005.cpp,内容如下:
#include"date.h"
intmain()
{
Dated1;//自动调用构造函数1
Dated2(2016);//自动调用构造函数2
Dated3(2016,10);//自动调用构造函数3
Dated4(2016,10,6);//自动调用构造函数4
d1.ShowDate();
d2.ShowDate();
d3.ShowDate();
d4.ShowDate();
return0;
}
运行结果是:
2016.5.1
2016.5.1
2016.10.1
2016.10.6
当然我们可以定义带缺省值的构造函数,将上述构造函数简化,下述程序的功能与上述程序相当:
#include
usingnamespacestd;
classDate
{
intYear,Month,Day;
public:
Date(inty=2016,intm=5,intd=1)
//带参数缺省值的构造函数
{
Year=y;Month=m;Day=d;
}
voidShowDate()
{
cout<}
};
intmain()
{
Dated1,d2(2016),d3(2016,10),d4(2016,10,6);
d1.ShowDate();
d2.ShowDate();
d3.ShowDate();
d4.ShowDate();
return0;
}
运行结果与上例一样。
返回ppt讲稿
例10.6定义学生类,利用构造函数初始化数据成员,利用析构函数做清理工作。
#include
#include
usingnamespacestd;
classStudent
{
charNum[10];//学号,注意:
用数组实现
char*Name;//姓名,注意:
用指针实现
intScore;//成绩
public:
Student(char*nump,char*namep,intscore)
{
if(nump)//在构造函数中,
{//不需要动态申请Num成员的空间
strcpy(Num,nump);
}
else
strcpy(Num,"");
if(namep)//在构造函数中,
{//需动态申请Name成员的空间
Name=newchar[strlen(namep)+1];
strcpy(Name,namep);
}
elseName=NULL;
Score=score;
cout<<"ConstructorCalled!
\n";
}
~Student()//在析构函数中,
{//需释放Name成员的空间
if(Name)delete[]Name;
cout<<"DesturctorCalled!
\n";
}
voidShow()
{
cout<cout<cout<}
};
intmain()
{
Studenta("040120518","George",80);
a.Show();
return0;
}
此程序运行结果是:
ConstructorCalled!
//调用构造函数时的输出
040120518George80
DesturctorCalled!
//调用析构函数时的输出
返回ppt讲稿
例10.7调用构造函数和析构函数的时机
#include
usingnamespacestd;
classDate
{
intYear,Month,Day;
public:
Date(inty=2000,intm=1,intd=1)//A,所有参数都有默认值
{
Year=y;Month=m;Day=d;
cout<<"Constructor:
";
ShowDate();
}
voidShowDate()
{
cout<}
~Date()
{
cout<<"Destructor:
";
ShowDate();
}
};
Dated4(2016,4,4);//全局对象(静态的)
voidfun()
{
cout<<"进入fun()函数!
\n";
staticDated2(2016,2,2);//局部静态对象
Dated3(2016,3,3);//局部动态对象
cout<<"退出fun()函数!
\n";
}
intmain()
{
cout<<"进入main()函数!
\n";
Dated1(2016,1,1);//局部动态对象
fun();
fun();
cout<<"退出main()函数!
\n";
return0;
}
此程序运行结果是:
Constructor:
2016.4.4//调用构造函数,产生d4对象
进入main()函数!
Constructor:
2016.1.1//调用构造函数,产生d1对象
进入fun()函数!
//第1次进入fun()函数,产生下述d2,d3对象
Constructor:
2016.2.2
Constructor:
2016.3.3
退出fun()函数!
//退出fun()函数,撤消d3对象,不撤消d2对象
Destructor:
2016.3.3
进入fun()函数!
//第2次进入fun()函数,再次产生d3对象
Constructor:
2016.3.3
退出fun()函数!
Destructor:
2016.3.3//退出fun()函数,撤消d3对象
退出main()函数!
//退出main()函数,撤消d1,d2,d4对象
Destructor:
2016.1.1
Destructor:
2016.2.2
Destructor:
2016.4.4
返回ppt讲稿
例10.9定义一个“平面坐标点”类,测试拷贝构造函数的调用。
//头文件"point.h"
classPoint
{
intx,y;
public:
Point(inta=0,intb=0)//缺省构造函数
{
x=a;y=b;
}
Point(Point&p);//拷贝构造函数原型说明
~Point()//析构函数
{
cout<}
voidShow()
{
cout<<"Point:
"<}
intGetx()
{returnx;}
intGety()
{returny;}
};
Point:
:
Point(Point&p)//定义拷贝构造函数
{
x=p.x;y=p.y;
cout<}
//文件Li1009.cpp
#include
u