C++继承——两点间距离计算

C++:继承——两点间距离计算

给出下面的一个基类框架:
class Point_1D
{ protected:
float x;//1D 点的x坐标
public:
Point_1D(float p = 0.0);
float distance(const Point_1D & p2);
}
以Point_1D为基类建立一个派生类Point_2D,增加一个保护数据成员:
float y;//2D平面上点的y坐标
以Point_2D为直接基类再建立一个派生类Point_3D,增加一个保护数据成员:
float z;//3D立体空间中点的z坐标
生成上述类并编写主函数,根据输入的点的基本信息,建立点对象,并能计算该点到原点的距离。
输入格式: 测试输入包含若干测试用例,每个测试用例占一行(点的类型(1表示1D点,2表示2D点,3表示3D点) 第一个点坐标信息(与点的类型相关) 第二个点坐标信息(与点的类型相关))。当读入0时输入结束,相应的结果不要输出。
输入样例:
1 -1 0
2 3 4 0 0
3 1 2 2 0 0 0
0
输出样例:
Distance from Point -1 to Point 0 is 1
Distance from Point(3,4) to Point(0,0) is 5
Distance from Point(3,3,3) to Point(0,0,0) is 3

使用IDE为VS2017

#include "stdafx.h"
#include 
#include 
using namespace std;
class Point_1D
{
protected:
 	float x;//1D 点的x坐标
public:
 	Point_1D(float p = 0.0) {};
 	void set_1D() 
	 { 
  	cin >> x; 
 	}
	 float distance(const Point_1D & p2) 
	 {
  	float a;
 	 a = fabs(x - p2.x);//求绝对值
 	 cout << "Distance from Point " << x << " to Point " << p2.x 
 	 << " is " << a << endl;
  	return a;
	 }
};
class Point_2D :public Point_1D 
{  
protected:
 	float y;
public:
 	void set_2D() 
 	{ 
  	set_1D(); //调用基类的set函数
  	cin >> y; 
 	} 
 	float distance(const Point_2D & p2) 
 	{
 	 float a;
 	 a = sqrt((x - p2.x)*(x - p2.x) + (y - p2.y)*(y - p2.y));
 	 //开平方根,求到坐标原点的距离
 	 cout << "Distance from Point(" << x << "," << y << ")
 	  to Point(" << p2.x << "," << p2.y << ") is " << a << endl;
 	 return a;
 	}
};
class Point_3D :public Point_2D 
{
protected:
 	float z;
public:
 	void set_3D() 
 	{ 
  	set_2D(); 
 	cin >> z; 
 	}
 float distance(const Point_3D & p2) 
 {
        float a;
  
        a = sqrt((x - p2.x)*(x - p2.x) 
        + (y - p2.y)*(y - p2.y) + (z - p2.z)*(z - p2.z));
  
        cout << 
        "Distance from Point(" << x << "," << y << "," << z << ") 
  	to Point(" << p2.x << "," << p2.y << "," << p2.z << ")is " 
  	<< a << endl;
  	return a;
 	}
};
int main()
{
 int type;
 Point_1D a1, a2;
 Point_2D b1, b2;
 Point_3D c1, c2;
 
 cin >> type;
 
 while (type)
 {
  switch (type)
  {
    case 1:a1.set_1D(); 
      	a2.set_1D(); 
      	a1.distance(a2); 
      	break;
    case 2:b1.set_2D(); 
      	b2.set_2D(); 
      	b1.distance(b2); 
      	break;
    case 3:c1.set_3D(); 
      	c2.set_3D(); 
     	c1.distance(c2); 
      	break;
  }
  	cin >> type;
 }
    return 0;
}

你可能感兴趣的:(C++学习)