l两点之间的距离--线段类

本文通过一个具体的C++程序实例,展示了成员函数、友元函数和一般函数的区别,并对比了它们在实现相同功能(计算两点间距离)时的不同用法。文中详细解释了这些函数如何与类进行交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*

*Copyright (c)2016,烟台大学计算机与控制工程学院

*All rights reserved.

*文件名称:main.cpp

*作 者:隋文韬

*完成日期:2016年4月21日

*版 本 号:v1.0 *

*问题描述:成员函数,友元函数和一般函数的区别

*/

#include<iostream>
#include<cmath>
using namespace std;
class CPoint//点类
{
private:
    double x;  //横坐标
    double y;  //纵坐标
public:
    CPoint(int  xx=0,int yy=0):x(xx),y(yy){}
    int getX(){return x;}
    int getY(){return y;}
    friend double  fri1(CPoint &p1,CPoint &p2);//友元函数

};
double fri1(CPoint &p1,CPoint &p2)//友元函数的实现
{
    double x=p1.x-p2.x;
    double y=p1.y-p2.y;
    return sqrt(x*x+y*y);
}


class CLine//直线类
{
public:
    CLine(CPoint xp1,CPoint xp2);
    double getLen(){return len;}
private:
    CPoint p1,p2;
    double len;
};
CLine::CLine(CPoint xp1,CPoint xp2):p1(xp1),p2(xp2)
{
double x=static_cast<double>(p2.getX()-p1.getY());
double y=static_cast<double>(p2.getY()-p1.getY());
len=sqrt(x*x+y*y);
}
double fri2(CPoint &p1,CPoint &p2)//一般函数的实现
{
   double x=p1.getX()-p2.getX();
   double y=p1.getY()-p2.getY();
   return sqrt(x*x+y*y);
}
int main()
{
    CPoint coordinatesOne(1,1),coordinatesTwo(4,5);
    CLine line(coordinatesOne,coordinatesTwo);
    cout<<"两点之间的距离为:";
    cout<<line.getLen()<<endl;
    cout<<"两点之间的距离为:";
    cout<<fri1(coordinatesOne,coordinatesTwo)<<endl;
    cout<<"两点之间的距离为:";
    cout<<fri2(coordinatesOne,coordinatesTwo)<<endl;
    return 0;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值