C++实训(1.1)

头文件1:define_class.h

#pragma once
#if!defined(define_class_H)
#define define_class_h
#include <iostream>
#include <cmath>
using namespace std;

//定义坐标点类
class Point
{
private:
double X, Y; //横、纵坐标 私有变量
public:
Point(double = 0.0, double = 0.0);
Point(Point &);
void Display()
{
cout << X << "," << Y << endl;
}
double Distance(Point&);

double getX()
{
return X;
}
double getY()
{
return Y;
}
};

class Line
{
private:
Point a, b; //线段类的两个端点
public:
Line(Point&, Point&);
void Display();
Line(Line &);
double Distance(); //两点间距离
};

#endif

头文件2:function.h

#pragma once
#if!defined(function_H)
#define function_h

//#include <iostream>
//#include <cmath>
#include "define_class.h"
using namespace std;

Point::Point(double a, double b)
{
X = a;
Y = b;
}
Point::Point(Point& a)
{
X = a.X;
Y = a.Y;
}

double Point::Distance(Point& a)
{
double dis;
dis = sqrt((X-a.X)* (X - a.X)+ (Y - a.Y) * (Y - a.Y));
return dis;
}

Line::Line(Point& a1, Point& a2) :a(a1), b(a2) //给Line的私有变量初始化
{
}

void Line::Display()
{
a.Display();
b.Display();
}

Line::Line(Line& m)
{
a = m.a;
b = m.b;
}
double Line::Distance()
{
double x, y;
x = a.getX() - b.getX();
y = a.getY() - b.getY();
return sqrt(x * x + y * y);
}

#endif

主程序:20200607_1.cpp 

#include <iostream>
#include <cmath>
#include "function.h"
using namespace std;

int main()
{
Point a;
Point b(8.9,9.8), c(34.5,67.8);
a = c; //调用复制构造函数
a.Display();
b.Display();

cout << "两点间距离:" << a.Distance(b)<<endl;

Line s(a, b);

Line s1(s);

s1.Display();

cout << "线段的长度:" << s1.Distance() << endl;

system("pause"); //暂停

return 1;
}

原文地址:https://www.cnblogs.com/duanqibo/p/13065103.html