第七周项目1 三种不同函数求两点间的距离

/*   
 *Copyright(c) 2016,烟台大学计算机学院   
 *All rights reserved.   
 *作    者:刘金石   
 *完成日期:2016年4月11日   
 *版本  号:v1.0   
 *问题描述:完成点类中求距离的任务,分别利用成员函数,友元函数和一般函数实现 
            分别写出三种实现方式代码。 
 *输入描述:无。   
 *输出描述:输出两点间的距离。   
*/
#include<iostream>                  //用成员函数实现
#include<cmath>
using namespace std;
class CPoint                   //点类
{
private:
    double x;
    double y;
public:
    CPoint(double xx=0,double yy=0):x(xx),y(yy){}               //构造函数
    double getX(){return x;}
    double getY(){return y;}
};
class Line                //线类
{
private:
    CPoint p1,p2;
    double len;
public:
    Line(CPoint xp1,CPoint xp2);
    void display();                                          //用成员函数实现
};
Line::Line(CPoint xp1,CPoint xp2):p1(xp1),p2(xp2)
{
    double x=p1.getX()-p2.getX();
    double y=p1.getY()-p2.getY();
    len=sqrt(x*x+y*y);
}
void Line::display()
{
    cout<<"两点间的距离为:"<<len<<endl;
}
int main()
{
    CPoint myp1(4,5),myp2(1,1);
    Line line(myp1,myp2);
    line.display();
    return 0;
}
#include<iostream>  //用友元函数实现
#include<cmath>
using namespace std;
class CPoint
{
private:
    double x;
    double y;
public:
    CPoint(double xx=0,double yy=0):x(xx),y(yy){}
    double getX(){return x;}
    double getY(){return y;}
};
class Line
{
private:
    CPoint p1,p2;
    double len;
public:
    Line(CPoint xp1,CPoint xp2);
    friend void display(Line &t);       //用友元函数实现
};
Line::Line(CPoint xp1,CPoint xp2):p1(xp1),p2(xp2)
{
    double x=p1.getX()-p2.getX();
    double y=p1.getY()-p2.getY();
    len=sqrt(x*x+y*y);
}
void display(Line &t)
{

    cout<<"两点间的距离为:"<<t.len<<endl;
}
int main()
{
    CPoint myp1(4,5),myp2(1,1);
    Line line(myp1,myp2);
    display(line);
    return 0;
}
#include<iostream>    //用一般函数实现
#include<cmath>
using namespace std;
class CPoint
{
private:
    double x;
    double y;
public:
    CPoint(double xx=0,double yy=0):x(xx),y(yy){}
    double getX(){return x;}
    double getY(){return y;}
};
class Line
{
private:
    CPoint p1,p2;
    double len;
public:
    Line(CPoint xp1,CPoint xp2);
    double getLen(){return len;}
};
Line::Line(CPoint xp1,CPoint xp2):p1(xp1),p2(xp2)
{
    double x=p1.getX()-p2.getX();
    double y=p1.getY()-p2.getY();
    len=sqrt(x*x+y*y);
}
void display(Line &t)     //用一般函数实现
{

    cout<<"两点间的距离为:"<<t.getLen()<<endl;
}
int main()
{
    CPoint myp1(4,5),myp2(1,1);
    Line line(myp1,myp2);
    display(line);
    return 0;
}

运行结果:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值