使用VC6打开考生文件夹下的源程序文件 modi1.cpp,但该程序运行时有错,请改正main()函数 中的错误,使程序的输出结果如下: Constructor. Default constructor. Area is 12

admin2018-10-23  18

问题 使用VC6打开考生文件夹下的源程序文件
modi1.cpp,但该程序运行时有错,请改正main()函数
中的错误,使程序的输出结果如下:
    Constructor.
    Default constructor.
    Area is 12
    Area is 0
    Area is 12
    注意:错误的语句在//******error******的下面,修改该语句即可。
1  #include<iostream.h>
2  class  CRectangle
3  {
4  private:
5    double length,width;
6  public:
7    CRectangle()
8    {
9    cout<<’’Default  constructor.\n’’;
10    }
11    CRectangle(double 1,double W)
12    {
13    length=1;width=w;
14    cout<<"Constructo.\n’’;
15    }
16    void Set(double 1,double w)
17    {
181    this->length=1;
19    this->width=w;
20    }
21    void GetArea()
22    {
23    cout<<’’Area is’’<<length*width<<end1;
24    }
25  };
26  void main()
27  {
28    CRectangle Rect1(3.0,4.0);
29    //******error******
30    CRectangle Rect2(1);
31    //******error******
32    CRectangle Rect3;
33    Rect1.GetArea();
34    //******error******
35    Rect2.Set(0);
36    Rect2.GetArea();
37    Rect3.GetArea();
38  }

选项

答案(1)CRectangle Rect2; (2)CRectangle Rect3(Rect1); (3)Rect2.Set(0,0);

解析 程序中定义了类CRectangle,有length和width两个成员变量,两个构造函数,Set()成员函数和GetArea()成员函数,Set()成员函数可以改变length和width的值,GetArea()成员函数在屏幕上打印length和width的积。
    (1)构造函数CRectangle()不带有参数,CRectangle(double 1,double w)带有2个参数,在创建对象时会自动调用构造函数,但是参数必须匹配,第1个标识下定义Rect2对象时,有一个参数,而类CRectangle()中并没有重载一个参数的构造函数,编译后出错,因此第1标识下应改为“CRectangle Rect2;”。
    (2)Rect3.GetArea()输出的结果和Rect1.GetArea()输出结果一致,因此对象Rect3和对象Rect1两者具有相同的length和width值,除定义Rect3对象之外没有改变Rect31的length和width值,因此Rect3成员变量的初始化是通过拷贝构造函数类实现的,即用Rect1对象去初始化Rect3,因此第2个标识下应改为“CRectangle Rect3(Rect1);”。
    (3)Rect2.GetArea()的输出结果为0,说明Rect2的成员变量length和width值至少一个为0,而Set()函数必须有两个参数,这里Rect2.Set(0)参数不匹配,应改为“Reet2.Set(0,0);”或者“Rect2.Set(0,5)”,两个参数当中至少一个为0即可。
转载请注明原文地址:https://kaotiyun.com/show/75Ap777K
0

最新回复(0)