问答题
使用VC6打开考生文件夹下的源程序文件modi3.cpp。其中定义的类并不完整,按要求完成下列操作,将类的定义补充完整。完成以下功能: (1)完成类Rect的构造函数,实现对变量left、right、top、bottom的初始化,缺省值都为0,请在注释//********1********后添加适当的语句。 (2)完成类Rectangle的构造函数,请在注释//********2********后添加适当的语句。 (3)完成计算矩形对角线长度函数Diagonal(),请在注释//********3********后添加适当的语句。 (4)完成计算周长函数Girth(),请在注释//********4********后添加适当的语句。 程序输出: 50 140 注意:增加代码,或者修改代码的位置已经用符号表示出来。请不要修改其他的程序代码。#include<iostream.h>#include<cmath>class Rectangle{public: int left , right , top , bottom; //********1******** { left=1; right=r; top=t; bottom=b; } //********2******** { left=rc.1eft; right=rc.right; top=rc.top; bottom=rc.bottom; } float Diagonal() { //********3******** return } int Girth() { //********4******** return }};int main(){ Rectangle rect(20,50,40,80); Rectangle rect2(rect); cout<<rect2.Diagonal()<<endl; cout<<rect2.Girth()<<endl; return 0;}
【正确答案】正确答案:(1)添加语句:Rectangle(int 1,int r,int t,int b) (2)添加语句:Rectangle(Rectangle&rc) (3)将“return”补充完整为:return sqrt((right—left)*(right—left)+(bottom—top)*(bottom—top)); (4)将“return”补充完整为:return 2*((right—left)+(bottom—top));
【答案解析】解析:(1)构造函数函数名和类名一致,构造函数可以重载,即多个构造函数有相同的名字不同的参数,显然题目当中两个构造函数均有参数,由函数体体内“left=1;right=r;top=t;bottom=b;”,说明l,r,t,b为构造函数的参数,因此第1标识处应添加“Rectangle(int l,int r,int t,int b)”。 (2)和题目1一样,构造函数名和类名一致,函数体内:“left=rc.left;right=re.right;top=re.top;bottom=rc.bottom;”显然rc是Rect对象,故该构造函数的参数为re对象,故第2标识处应添加“Rectangle(Rectangle&rc)”。 (3)由对象的left、fight、top、bottom值可以求得矩形的长和宽,因此可采用勾股定理计算对角线长度,即第3标识处补充完整为:return sqrt((right.1eft)*(fight—left)+(bottom-top)*(bottom—top))。 (4)同样的周长可由长和宽的数值计算得到,长和宽之和的两倍即周长,第4标识处补充完整为:return 2*((right—left)+(bottom—top))。