3-7 類的友元函數的應用

3-7 類的友元函數的應用

Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

通過本題目的練習可以掌握類的友元函數的定義和用法
要求設計一個點類Point,它具有兩個double型的數據成員x,y。爲該類設計構造函數。併爲其添加一個友元函數用於計算並輸出兩點間的距離;再添加一個輸出成員函數用於輸出點的信息。
 
 
並編寫主函數,實現以下的輸入輸出內容。

Input

4double型的數,中間用一個空格間隔。

Output

輸出數據共3行,前兩行用於顯示要求距離的兩個點的信息,第三行顯示兩點的距離。

Example Input

5 6 2 3

Example Output

The first point is the coordinate:X=5,Y=6
The second point is the coordinate:X=2,Y=3
The distance between the two points is:4.24264

Hint


Author


#include <iostream>
#include <cmath>
using namespace std;

class Point
{
private:
    double x;
    double y;
public:
    Point(double a = 0, double b = 0)                   //構造函數
    {
        x = a;
        y = b;
    }
    void showpoint1()                                   //輸出點一座標    {
        cout << "The first point is the coordinate:X=" << x << ",Y=" << y << endl;
    }
    void showpoint2()                                   //輸出點二座標
    {
        cout << "The second point is the coordinate:X=" << x << ",Y=" << y << endl;
    }
    friend void showdis(Point &, Point &);              //友元
};

void showdis(Point & p1, Point & p2)
{
    double dis = sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
    cout << "The distance between the two points is:" << dis << endl;
}

int main()
{
    double x1, x2, y1, y2;
    cin >> x1 >> y1 >> x2 >> y2;
    Point p1(x1, y1);
    Point p2(x2, y2);
    p1.showpoint1();
    p2.showpoint2();
    showdis(p1, p2);
    return 0;
}


發佈了111 篇原創文章 · 獲贊 12 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章