Point类的实现——C++学习笔记

点类的定义

point.h:

//point.h

#ifndef _POINT_              
#define _POINT_

//点类的定义
class Point {
public:
	//默认构造
	Point();
	//构造函数
	Point(double, double);
	//拷贝构造
	Point(const Point&);
	//获取点x,y坐标
	double getX();					
	double getY();
	//设置点坐标
	void setPoint(double, double);
	//重载赋值运算
	void operator=(const Point&);
	//打印点坐标			
	void show();									

private:
	double x, y;
};
#endif  

point.cpp:

//point.cpp

#include<iostream>
#include "point.h"

using namespace std;

//点类的实现
Point::Point() {									//默认构造
	this->x = 0;
	this->y = 0;
}
Point::Point(double x, double y) {					//构造函数
	this->x = x;
	this->y = y;
}
Point::Point(const Point& p){						//拷贝构造
	this->x = p.x;
	this->y = p.y;
}							
	
double Point::getX() { return x; }					//获取点x坐标
double Point::getY() { return y; }					//获取点y坐标

void Point::setPoint(double x, double y){			//设置点坐标

	this->x = x; 
	this->y = y;
}

void Point::operator=(const Point& p) {				//重载赋值运算
	this->x = p.x;
	this->y = p.y;
}

void Point::show(){									//打印点坐标
	cout << "(" << x << "," << y << ")"<<endl;
}

主函数:

//main
#include<iostream>
#include "point.h"
using namespace std;

int main() {

	Point a;
	Point b(1.2, 2.3);
	Point c = b;

	a = c;
	double m = 8;

	b.setPoint(5, m);

	double x = b.getX(), y = b.getY();
	cout << x << "  " << y << endl;
	a.show();
	a.show();
	c.show();
	return 0;
}
  • 4
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,我来为您解答。 首先,我们需要定义一个 `Point` ,表示一个点的坐标。这个可以有两个私有成员变量 `x` 和 `y`,分别表示横坐标和纵坐标。然后,我们需要定义一个 `Line` ,表示一条直线,可以由两个点确定。这个可以有两个私有成员变量 `p1` 和 `p2`,分别表示直线上的两个点。 接下来,我们可以在 `Point` 中定义一个公有成员函数 `distanceTo`,用于计算当前点和另一个点之间的距离。这个函数接受一个 `Point` 型的参数,表示另一个点。函数的实现可以使用勾股定理,计算两点之间的距离。 最后,在 `Line` 中定义一个公有成员函数 `distance`,用于计算直线上两点之间的距离。这个函数可以调用 `Point` 中的 `distanceTo` 函数,计算出两个点之间的距离。 下面是代码示例: ```cpp #include <iostream> #include <cmath> using namespace std; class Point { private: double x, y; // 点的坐标 public: Point(double _x, double _y): x(_x), y(_y) {} double distanceTo(Point p) { return sqrt(pow(x - p.x, 2) + pow(y - p.y, 2)); } }; class Line { private: Point p1, p2; // 直线上的两个点 public: Line(Point _p1, Point _p2): p1(_p1), p2(_p2) {} double distance() { return p1.distanceTo(p2); } }; int main() { Point p1(0, 0); Point p2(3, 4); Line line(p1, p2); cout << "The distance between (" << p1.distanceTo(p2) << ")" << endl; cout << "The distance on the line is (" << line.distance() << ")" << endl; return 0; } ``` 运行结果: ``` The distance between (5) The distance on the line is (5) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

渊鱼L

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值