天天看點

平面上的點——Point類 (II)

Description

在數學上,平面直角坐标系上的點用X軸和Y軸上的兩個坐标值唯一确定。現在我們封裝一個“Point類”來實作平面上的點的操作。

根據“append.cc”,完成Point類的構造方法和show()方法,輸出各Point對象的構造和析構次序。

接口描述:

Point::show()方法:按輸出格式輸出Point對象。

Input

輸入多行,每行為一組坐标“x,y”,表示點的x坐标和y坐标,x和y的值都在double資料範圍内。

Output

輸出每個Point對象的構造和析構行為。對每個Point對象,調用show()方法輸出其值:X坐标在前,Y坐标在後,Y坐标前面多輸出一個空格。每個坐标的輸出精度為最長16位。輸出格式見sample。

C語言的輸入輸出被禁用。

Sample Input

1,2
3,3
2,1
           

Sample Output

Point : (0, 0) is created.
Point : (1, 2) is created.
Point : (1, 2) Point : (1, 2) is erased.
Point : (3, 3) is created.
Point : (3, 3)
Point : (3, 3) is erased.
Point : (2, 1) is created.
Point : (2, 1)
Point : (2, 1) is erased.
Point : (0, 0) is copied.
Point : (1, 1) is created.
Point : (0, 0) Point : (1, 1)
Point : (0, 0) Point : (1, 1) is erased.
Point : (0, 0) is erased.
Point : (0, 0) is erased.
           

HINT

思考構造函數、拷貝構造函數、析構函數的調用時機。

append.cc

int main()
{
    char c;
    double a, b;
    Point q;
    while(std::cin>>a>>c>>b)
    {
        Point p(a, b);
        p.show();
    }
    Point q1(q), q2(1);
    q1.show();
    q2.show();
    q.show();
}
           

答案

#include <iostream>
#include<iomanip>
using namespace std;
class Point
{
private:
    double x,y;
public:
    Point()
    {
        x=0;
        y=0;
        cout<<setprecision(16)<<"Point : (0, 0) is created."<<endl;
    }
    Point(int _x,int _y)
    {
        x = _x;
        y = _y;
        cout<<setprecision(16)<<"Point : ("<<x<<", "<<y<<")is created."<<endl;
    }
    Point(int _x)
    {
        x=_x;
        y=_x;
        cout<<setprecision(16)<<"Point : ("<<x<<", "<<y<<")is copied."<<endl;

    }
    ~Point ()
    {
        cout<<setprecision(16)<<"Point : ("<<x<<", "<<y<<")is erased."<<endl;
    }
    Point(Point const &p)
    {
        x=p.x;
        y=p.y;
        cout<<setprecision(16)<<"Point : ("<<x<<", "<<y<<")is copied."<<endl;

    }
    void show()
    {
        cout<<setprecision(16)<<"Point : ("<<x<<", "<<y<<")"<<endl;
    }
};