您好,欢迎访问三七文档
当前位置:首页 > 行业资料 > 冶金工业 > 华科C++第七次上机作业
第七次上机作业1、范例:设计并测试一个矩形类(Rectangle)。属性为矩形的左下角与右上角的坐标,矩形水平放置。操作为计算矩形的周长和面积。2、#includecmath3、#includeiostream4、usingnamespacestd;5、classRectangle{6、doubleleft,top;7、doubleright,bottom;8、public:9、Rectangle(doublel=0,doublet=0,doubler=0,doubleb=0);10、~Rectangle(){};11、voidAssign(doublel,doublet,doubler,doubleb);12、voidShow();13、doubleArea();14、doublePerimeter();};15、Rectangle::Rectangle(doublel,doublet,doubler,doubleb){16、left=l;top=t;17、right=r;bottom=b;}18、voidRectangle::Assign(doublel,doublet,doubler,doubleb){19、left=l;top=t;20、right=r;bottom=b;}21、voidRectangle::Show(){22、coutleft-toppointis(left,top)\n;23、coutright-bottompointis(right,bottom)endl;}24、doubleRectangle::Area(){25、returnfabs((right-left)*fabs(bottom-top));26、}27、doubleRectangle::Perimeter(){28、return2*(fabs(right-left)+fabs(bottom-top));29、}30、intmain(){31、Rectanglerect;32、rect.Show();33、rect.Assign(100,200,300,400);34、rect.Show();35、Rectanglerect1(0,0,200,200);36、rect1.Show();37、rect1.Assign(100,200,300,400);38、rect1.Show();39、coutÃæ»ýrect.Area()'\t'Öܳ¤rect.Perimeter()endl;40、coutÃæ»ýrect1.Area()'\t'Öܳ¤rect1.Perimeter()endl;41、return0;}42、(1)将Rectangle(doublel=0,doublet=0,doubler=0,doubleb=0);改为Rectangle(doublel,doublet,doubler,doubleb);程序仍能正确运行吗?为什么?答:无法正确运行,因为数据成员没有初值。(2)注意成员函数voidShow()、doubleArea()、doublePerimeter()的使用,因为在第三章如果需编写类似功能的一般函数是需要带参数(形参)的。而在此处作为类的成员函数又不需要带参数。思考为什么?答:构造函数是隐式调用的(3)理解voidAssign(doublel,doublet,doubler,doubleb);函数的作用。将Rectangle(doublel=0,doublet=0,doubler=0,doubleb=0);改为Rectangle(doublel,doublet,doubler,doubleb);这时,有人认为Rectangle(doublel,doublet,doubler,doubleb)和voidAssign(doublel,doublet,doubler,doubleb)的功能相同,那么Assign函数能否去掉呢?请试一试,结果会怎样?答:不能,结果无法运行。2、定义一个圆类(Circle),要求用两种方法定义:方法一:要求属性为半径,操作为计算圆的周长和面积。#includeiostream#includecmathusingnamespacestd;constdoublePI=3.14;classCircle{private:doubleRadius;public:Circle(doubler=0);~Circle(){};voidAssign(doubler);doublezc();doublemj();};Circle::Circle(doubler){Radius=r;}voidCircle::Assign(doubler){Radius=r;}doubleCircle::zc(){return(PI*Radius*2);}doubleCircle::mj(){return(PI*Radius*Radius);}intmain(){Circleyuan;yuan.Assign(13.45);cout周长yuan.zc()endl;cout面积yuan.mj()endl;return0;}方法二:要求属性为半径(radius)、圆周长和面积,操作为输入半径,并计算周长、面积,输出半径、周长和面积。要求定义构造函数(以半径为参数,缺省值为0,周长和面积在构造函数中生成)和拷贝构造函数。
本文标题:华科C++第七次上机作业
链接地址:https://www.777doc.com/doc-5345842 .html