C++継承——2点間距離計算
15007 ワード
C++:継承-2点間距離計算
次のベースクラスフレームワークを示します:class Point_1 D{protected:float x;//1 D点のx座標public:Point_1 D(float p=0.0);float distance(const Point_1 D&p 2);}Point_で1 Dベースクラスの派生クラスPoint_を作成する2 D、保護データメンバーを追加:float y;//2 D平面上の点のy座標はPoint_2 D直接ベースクラスの派生クラスPoint_を再構築3 D、保護データメンバーを追加する:float z;//3 D立体空間における点のz座標は上記クラスを生成して主関数を記述し,入力した点の基本情報に基づいて点オブジェクトを確立し,その点から原点までの距離を計算できる.入力フォーマット:テスト入力にはいくつかのテスト例が含まれています.各試験例は1行を占める(点の種類(1は1 D点、2は2 D点、3は3 D点)第1の点座標情報(点の種類に関する)第2の点座標情報(点の種類に関係).0を読み込むと入力が終了し、その結果は出力されない.入力サンプル:1-0 2 3 4 0 3 1 2 2 0 0 0 0 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を使用してVS 2017
次のベースクラスフレームワークを示します:class Point_1 D{protected:float x;//1 D点のx座標public:Point_1 D(float p=0.0);float distance(const Point_1 D&p 2);}Point_で1 Dベースクラスの派生クラスPoint_を作成する2 D、保護データメンバーを追加:float y;//2 D平面上の点のy座標はPoint_2 D直接ベースクラスの派生クラスPoint_を再構築3 D、保護データメンバーを追加する:float z;//3 D立体空間における点のz座標は上記クラスを生成して主関数を記述し,入力した点の基本情報に基づいて点オブジェクトを確立し,その点から原点までの距離を計算できる.入力フォーマット:テスト入力にはいくつかのテスト例が含まれています.各試験例は1行を占める(点の種類(1は1 D点、2は2 D点、3は3 D点)第1の点座標情報(点の種類に関する)第2の点座標情報(点の種類に関係).0を読み込むと入力が終了し、その結果は出力されない.入力サンプル:1-0 2 3 4 0 3 1 2 2 0 0 0 0 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を使用してVS 2017
#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;
}