使用VC6打开考生文件夹下的源程序文件modi3.cpp,其中定义了用于表示矩形的CRect类,但类CRect的定义并不完整。请按要求完成下列操作,将类CRect的定义补充完成。
(1)定义私有数据成员leftPoint、topPoint、rightPoint、bottomPoint,分别用于表示矩形左上角及右下角的点的坐标,它们都是double型的数据。请在注释//********1********之后添加适当的语句。
(2)完成默认构造函数CRect的定义,指定缺省实参为0,都是double型的数据。请在注释//********2********之后添加适当的语句。
(3)定义函数体为空的析构函数。请在注释//********3********之后添加适当的语句。
(4)在main()函数中定义CRect类的实例rect2,并把rectl 的值赋给rect2。请在注释//********4********之后添加适当的语句。
注意:除在指定位置添加语句之外,请不要改动程序中的其他内容。
1 #include< iostream.h >
2 class CRect
3 {
4 private:
5 //********1********
6
7 public:
8 //********2********
9
10 //********3********
11
12 vold SetPoints(double,double,double,double);
13 void SetLeftPoint(double m){leftPoint=m;}
14 void SetRightP0int(double m)( rightPoint=m;}
15 void SetTopPoint(double m){topPoint=m;}
16 void SetBottomPoint(double m){bottomPoint=m;}
17 void Display();
18 };
19
20 CRect::CRect(double 1,double t,double r,double b)
21 {
22 leftPoint=1; topPoint=t;
23 rightPoint=r;bottomPoint=b;
24 }
25 void CRect::SetPointS(double 1,double t,double r,double b)
26 {
27 leftPoint=1;topPoint=t;
28 rightPoint=r;bottomP0int=b;
29 }
30 void CRect::Display()
31 {
32 cout< < ''left-top point is(''< < leftPoint< < '',''< < topPoint< < '')''< < '\n';
33 cout< < ''right-bottom point is(''< < rightPoint< < '',''< < bottomPoint< < '')''< < '\n';
34 }
35 void main() {
36 CRect rect0;
37 rect0.Display();
38 rect0.SetPoints(20,20.6,30,40);
39 rect0.Display();
40 CRect rect1(0,0,150,150);
41 rect1.SetTopPoint(10.5);
42 rect1.SetLeftPoint(10.5);
43 //********4********
44
45 rect2.Display();
46 }
【正确答案】(1)添加语句:double leftPoint,topPoint,rightPoint,bottomPoint;
(2)添加语句:CRect(double leftPoint=0,double topPoint=0,double rightP0int=0,double bottomPoint=0);
(3)添加语句:~CRect(){};
(4)添加语句:CRect rect2(rect1);
【答案解析】程序中定义了一个表示矩形的类CRect,该类中定义了私有数据成员leftPoint、topPoint、rightPoint、bottomPoint,分别用于表示矩形左上角及右下角的点的坐标且它们的数据类型都是double型,类CRect有多个成员函数,SetPoints(),SetLeftPoint()函数可改变成员变量leftPoint的值,而SetRightPoint()成员函数可改变rightPoint的值,SetTopPoint()可改变topPoint的值,SetBottomPoint()改变bottomPoint的值,Display()成员函数显示成员变量的值。
(1)第1个标识下完成私有数据成员lettPoint、topPoint、rightPoint、bottomPoint的定义,均为double型的变量,故第1个标识下应添加“doubleleftPoint,topPoint,rightPoint,bottomPoint;”。
(2)构造函数完成成员变量的初始化,类CRect的默认构造函数并初始化double型私有数据成员leftPoint、topPoint、rightPoint、bottomPoint为0,故第2个标识下应添加“CRect(double leftPoint=0,doubletopPoint=0,double rightPoint=0,doublebottomPoint=0);”。
(3)析构函数名和类名一致,并在前面加“~”以和构造函数区别,该析构函数体为空,故第3个标识下应添加“~CRect(){};”,虽然该函数体为空,但是“{}”必须保留。
(4)主函数中类CRect的对象rect2是通过复制构造函数将rect1的值赋值给它实现初始化的,而rect1的初始化直接调用自定义构造函数,第4个标识下应添加“CRect rect2(rect1);”。