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

线类的定义

line.h:

#pragma once
//line.h
#include "point.h"

class Line {
public:
	//默认构造
	Line();
	//构造函数
	Line(Point, Point);
	//拷贝构造
	Line(const Line&);
	//获取点端点坐标
	Point get1();
	Point get2();
	//设置线端点
	void setLine(Point, Point);
	//重载赋值运算
	void operator=(const Line&);
	//打印线端点坐标			
	void show();
	//计算线段长度	
	double lineLength();

private:
	Point p_1, p_2;
	double l_L;
};

line.cpp:

#include<iostream>
#include "line.h"
#include<math.h>

using namespace std;
//默认构造
Line::Line() {
	this->p_1 = p_1;
	this->p_2 = p_2;
	this->l_L = lineLength();
}

//构造函数
Line::Line(Point p_1, Point p_2) {
	this->p_1 = p_1;
	this->p_2 = p_2;
	this->l_L = lineLength();
}

//拷贝构造
Line::Line(const Line& l) {
	this->p_1 = l.p_1;
	this->p_2 = l.p_2;
	this->l_L = l.l_L;
}

//获取端点坐标
Point Line::get1() {
	return p_1;
}
Point Line::get2() {
	return p_2;
}

//设置线端点
void Line::setLine(Point p1, Point p2) {
	this->p_1 = p1;
	this->p_2 = p2;
	l_L = lineLength();
}

//重载赋值运算
void Line::operator=(const Line& l) {
	this->p_1 = l.p_1;
	this->p_2 = l.p_2;
	this->l_L = l.l_L;
}

//打印线端点坐标
void Line::show() {
	cout << "线起点:";
	this->p_1.show();
	cout << "线终点:";
	this->p_2.show();
	cout << "长度:"<<l_L<<endl<<endl;
}

//计算线段长度	
double Line::lineLength() {
	double dx = pow(p_1.getX() - p_2.getX(), 2);
	double dy = pow(p_1.getY() - p_2.getY(), 2);
	return pow(dx+dy,0.5);
}

main:

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

void lineTest() {
	Point a;
	Point b(1, 3);
	Line l1;
	Line l2(a, b);
	Line l3;
	l3 = l2;
	l1.setLine(a, b);
	Point p1 = l2.get1();
	Point p2 = l2.get2();

	p1.show();

	l1.show();
	l2.show();
	l3.show();
}

int main() {
	lineTest();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

渊鱼L

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

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

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

打赏作者

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

抵扣说明:

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

余额充值