不喜勿喷,我想加深一下自己对代码的熟悉程度,也想和大家分享学习成果。
思路:定义一个点point类用来设置两点,并用print打印两点的距离。
代码:
//
计算两点距离.cpp
#include <iostream>
#include "Point.h"
#include "Distance.h"
using namespace std;
int main()
{
cout << "欢迎使用!!!\n";
Point mp1(2, 3), mp2(4, 3);
Distance mdist(mp1, mp2);
cout << "两点距离为: " << mdist.GetDis() << endl;
return 0;
}
}
//
Point.h
#include <iostream>
using namespace std;
class Point
{
public:
Point(double xi,double yi)
{
x = xi;
y = yi;
}
double GetX() { return x; }//接口,返回私有数据成员x
double GetY() { return y; }//接口,返回私有数据成员y
~Point()
{
cout << "已调用析构函数" << endl;
}
private:
double x, y;
};
//
Distance.h
#include "Point.h"
class Distance
{
public:
Distance(Point xp1,Point xp2);
double GetDis() { return dist; }//返回距离
~Distance();
private:
Point p1, p2;//设置两个私有点成员
double dist;
};
//
Distance.cpp
#include "pch.h"
#include "Distance.h"
#include <cmath>
#include <iostream>
using namespace std;
Distance::Distance(Point xp1,Point xp2)//计算距离
:p1(xp1),p2(xp2)
{
double x = double(p1.GetX() - p2.GetX());
double y = double(p1.GetY() - p2.GetY());
dist = sqrt(x*x + y * y);
}
Distance::~Distance()
{
}
运行结果就不放图了,喜欢的可以拿代码回去试一下呀,手打不易,不喜勿喷。
嘻嘻,小小成就感got