设计并实现一个平面点类 Point

要求:
1)用x、y两个坐标值表示一个点;
2)正确初始化每个点,默认坐标值为原点;
3)计算点到原点的距离;
4)计算到另一个点的距离;
5)获取点的 x、y坐标值;
6)设置点的 x、y坐标;
7)移动点到新位置。
主函数及输出示例如下:

int main()
{
	Point p1(1,3), p2(4,5), p3(2);
	cout<<"p1: "<<p1.getX()<<","<<p1.getY()<<endl;
	cout<<"p1 to origin:"<<p1.distance()<<endl;
	cout<<"p2:"<<p2.getX()<<","<<p2.getY()<<endl;
	cout<<"p1 to p2:"<<p1.distance(p2)<<endl;
	p1.moveto(p3);
	cout<<"p1 moveto p3:"<<p1.getX()<<","<<p1.getY()<<endl;
	p1.moveto(4, 5);
	cout<<"p1 moveto (4, 5):"<<p1.getX()<<","<<p1.getY()<<endl;
}

解题思路:
首先创建一个Point类来表示二维平面上的一个点,使该类具有私有成员变量x,y,分别代表点的横坐标和纵坐标。接着提供一个默认构造函数,初始化为原点,带两个参数的构造函数,带单个参数的构造函数,y的坐标默认设置为0;正确初始化每个点,计算点到原点的距离,计算点到另一个点的距离;获取点的 x、y坐标值,设置点的 x、y坐标,移动点到新位置的两种方法,一个接受另一个Point对象作为参数,另一个接受两个坐标作为参数。
代码:

#include <iostream>
#include <cmath>
using namespace std;
class Point
{
private:
    double x,y;
public:
    Point():x(0),y(0){}
    Point(double xa,double ya):x(xa),y(ya){}
    Point(double xa) :x(xa),y(0){}
    double distance() const
    {
        return sqrt(x * x + y * y);
    }
    double distance(const Point& P)const
    {
        double dx = x - P.x;
        double dy = y - P.y;
        return sqrt(dx * dx + dy * dy);
    }
    double getX() const
    {
        return x;
    }
    double getY() const
    {
        return y;
    }
    void setX(double xa)
    {
       this->x = xa;
    }
    void setY(double ya)
    {
        this->y = ya;
    }
    void moveto(const Point& P)
    {
        x = P.x;
        y = P.y;
    }
    void moveto(double xa,double ya)
    {
        this->x = xa;
        this->y = ya;
    }
};
int main()
{
    Point p1(1,3),p2(4,5),p3(2);
    cout << "p1: "<<p1.getX()<<","<<p1.getY()<<endl;
    cout << "p1 to origin:"<< p1.distance()<<endl;
    cout << "p2: "<<p2.getX()<<","<<p2.getY()<<endl;
    cout << "p1 to p2:"<<p1.distance(p2)<<endl;
    p1.moveto(p3);
    cout<< "p1 moveto p3:"<<p1.getX()<<","<<p1.getY()<<endl;
p1.moveto(4,5);
    cout<<"p1 moveto (4,5):"<<p1.getX()<<","<<p1.getY()<<endl;
}

运行结果截图:
在这里插入图片描述

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值