使用VC6打开考生文件夹下的工程MyProj4。此工程包含一个源程序文件 MyMain4.cpp,该程序将通过把类Distance定义为类Point的友元类来实现计算两点之间距离的功能。但程序中定义的类并不完整。请按要求完成下列操作,把类的定义补充完整。

admin2009-01-15  29

问题 使用VC6打开考生文件夹下的工程MyProj4。此工程包含一个源程序文件 MyMain4.cpp,该程序将通过把类Distance定义为类Point的友元类来实现计算两点之间距离的功能。但程序中定义的类并不完整。请按要求完成下列操作,把类的定义补充完整。
   ①把类Distance定义为类Point的友元类。请在注释“//**1**”之后添加适当的语句。
   ②定义类Point的构造函数,完成给私有数据成员x和y的赋值,并且两个参数的默认值都为0。请在注释“//**2**”之后添加适当的语句。
   ③完成类Distance的成员函数Dis(Point &p,Point &q)的定义,并在其中计算点p、q之间的距离,并且返回结果。假设两点之间的距离distance=sqrt((p.x-q.x)* (p.x-q.x)+(p.y-q.y)*(p.y-q.y))。请在注释“//**3**”之后添加适当的语句。
   源程序文件MyMain4.cpp中的程序清单如下:
   //MyMain4. cpp
   #include<iostream>
   #include<cmath>
   using namespace std;
   class Point
   {
   public:
      / /* * 1 * *
      / /定义类 Point 的构造函数
      / /* * 2 * *
      void pint()
      {
         cout<<"x="<<x<<end1;
         cout<<"y="<<y<<end1;
      }
   private:
      float x,y;
   };
   class Distance
   {
   public:
      float Dis(Point &p, Point &q);
   };
   float Distance  ::  Dis(Point &p, Point &q)
   {
     //* * 3 * *
   }
   int main ( )
   {
      Point p(10,10),q(20,20);
      Distance d;
      cout<<d.Dis(p,q)<<end1;
      return 0;
   }

选项

答案类Point的定义如下: class Point { public: friend class Distance; Point (float a=0, float b=0) { x=a; y=b; } void pint() { cout<<"x="<<x<<end1; cout<<"y="<<y<<end1; } private: float x,y; };

解析 此道综合应用题主要考核友元类的定义与使用。
   ①第1处是完成友元类的声明,根据友元类的声明格式已知此处可填入:
   friend class Distance;
   ②第2处是完成类Point的构造函数,此处还要注意类Point的构造函数中还应该有参数默认值。此处应填入:
   Point(float a=0,float b=0){x=a;y=b}
   ③第3处是完成类Distance成员函数Dis()的定义,函数Dis()的功能是计算两点之间的距离。根据题目给出的计算公式,已知第3处应填入:
   float result;result=sqrt((p.x-q.x)*(p.x-q.x)+(p.y-q.y)*(p.y-q.y));return result;
转载请注明原文地址:https://kaotiyun.com/show/tKID777K
0

最新回复(0)