C++ 编写点坐标(Point)的类

2024-12-02 11:59:53
推荐回答(1个)
回答1:

#include
#include

/*
该类可以提供移动,求到另一点的距离,
获取X坐标和Y坐标等操作,也可以设置X坐标和Y坐标的值。
要求有拷贝构造函数。数据成员为X坐标和Y坐标。
*/
using namespace std;

class Point{
public:
Point(); //不带参数构造函数
Point(int X, int Y); //带参数的构造函数
Point(const Point &p); //拷贝构造函数;
int getX(); //获取横坐标
int getY(); //获取纵坐标
void setX(int iX); //设置横坐标
void setY(int iY); //设置纵坐标
float distance(Point p1, Point p2); //计算两点的距离
protected:

private:
int x; //横坐标
int y; //纵坐标
};

int main()
{
Point pos;
Point pt(10, 10);
Point pts(pt);
cout << "获取pos的坐标值" << endl;
cout << "X:" << pos.getX() << endl;
cout << "Y:" << pos.getY() << endl;
pos.setX(20);
pos.setY(20);
cout << "获取pos的设置后的坐标值" << endl;
cout << "X:" << pos.getX() << endl;
cout << "Y:" << pos.getY() << endl;

cout << "获取pt的坐标值" << endl;
cout << "X:" << pt.getX() << endl;
cout << "Y:" << pt.getY() << endl;

cout << "获取pts的坐标值" << endl;
cout << "X:" << pos.getX() << endl;
cout << "Y:" << pos.getY() << endl;

cout << "输出pos与pt之间的距离" << endl;
cout << "X:" << pos.distance(pos, pt) << endl;

return 0;
}

Point::Point()
{
x = 0;
y = 0;
}

Point::Point(int X, int Y)
{
x = X;
y = Y;
}

Point::Point(const Point &p)
{
x = p.x;
y = p.y;
}

int Point::getX()
{
return x;
}

int Point::getY()
{
return y;
}

void Point::setX(int iX)
{
x = iX;
}

void Point::setY(int iY)
{
y = iY;
}

float Point::distance(Point p1, Point p2)
{
float dist;

dist = sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));
return dist;
}