构造函数Word文件下载.docx
《构造函数Word文件下载.docx》由会员分享,可在线阅读,更多相关《构造函数Word文件下载.docx(12页珍藏版)》请在冰点文库上搜索。
![构造函数Word文件下载.docx](https://file1.bingdoc.com/fileroot1/2023-5/8/623d32a0-017c-43a5-9422-c16b7e894c00/623d32a0-017c-43a5-9422-c16b7e894c001.gif)
学习掌握定义构造函数与析构函数的方法。
学习把握默认构造函数的意义。
了解类成员初始化,掌握构造与析构类成员的方式。
2、实验内容
(1)
创建一个Employee类,该类中用字符数组存放Employee的信息,如姓名、地址、市、省、及邮政编码;
每个成员函数的定义放在类定义之外;
成员函数包括改变姓名数据成员等;
构造函数完成成员数据的初始化;
用Display()函数将完整的对象数据打印出来;
其中数据成员是保护的,成员函数是公共的。
#include<
iostream>
string.h>
stdio.h>
usingnamespacestd;
classEmployee
{
public:
Employee(charn[20],chara[50],chars[20],charsh[20],charp[7]);
voidChangeName(charch_name[20]);
voidDisplay();
protected:
charname[20];
charaddress[50];
charshi[20];
charsheng[20];
charpost[7];
};
Employee:
:
Employee(charn[20],chara[50],chars[20],charsh[20],charp[7])
if(strlen(n)<
=19&
&
strlen(a)<
=49&
strlen(s)<
strlen(sh)<
strlen(p)==6)
strcpy(name,n),strcpy(address,a),strcpy(shi,s),strcpy(sheng,sh),strcpy(post,p);
}
voidEmployee:
ChangeName(charch_name[20])
if(strlen(ch_name)<
=19)
strcpy(name,ch_name);
Display()
char*p;
cout<
<
"
姓名:
endl;
for(p=name;
*p!
='
\0'
;
p++)
*p;
地址:
for(p=address;
市:
for(p=shi;
省份:
for(p=sheng;
邮政编码:
for(p=post;
voidmain()
charn[20],a[50],s[20],sh[20],p[7];
cout<
请输入姓名:
gets(n);
请输入地址:
gets(a);
请输入市区:
gets(s);
请输入省份:
gets(sh);
请输入邮政编码:
gets(p);
Employeeyu(n,a,s,sh,p);
yu.Display();
请输入您需要改变的名字:
charnameChange[20];
gets(nameChange);
yu.ChangeName(nameChange);
(2)设计一个表示矩形的类Rect,其矩形成员长float*Length,宽float*Width为指针变量,设计相应成员函数,实现下列功能:
①构造函数设置长和宽(默认为1)。
②复制构造函数用老对象生成新对象。
③set()函数设置长和宽(默认为0)。
④计算并返回长方形的周长。
⑤计算并返回长方形的面积。
⑥析构函数释放动态分配的长和宽。
编制主程序应用指针建立对象测试类。
iostream.h>
classRect{
float*Length,*Width;
Rect(floata=1,floatb=1);
Rect(Rect&
);
voidset(floata=0,floatb=0);
floatperi();
floatarea();
~Rect(){deleteLength;
deleteWidth;
Rect:
Rect(floata,floatb)
if(a>
0&
b>
0)
Length=newfloat(a),Width=newfloat(b);
else
您输入的长宽不符规则:
Rect(Rect&
p)
Length=newfloat(*(p.Length)),Width=newfloat(*(p.Width));
voidRect:
set(floata,floatb)
floatRect:
peri()
return(2*((*Length)+(*Width)));
area()
return((*Length)*(*Width));
利用构造函数构造对象"
floatlength,width,peri,area;
请输入长:
cin>
>
length;
请输入宽:
width;
Rectyu(length,width);
该矩形的周长为:
peri=yu.peri();
peri<
该矩形的面积为:
area=yu.area();
area<
利用set函数构造对象"
Rectysb;
ysb.set(length,width);
peri=ysb.peri();
area=ysb.area();
利用拷贝构造函数构造对象"
Rectt(ysb);
peri=t.peri();
area=t.area();