//例:使用成员函数、友元函数和一般函数的区别
#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){}
void input();
friend void display2(CPoint &,CPoint &);
void Distance1(CPoint p) const;
void setdis();
double getx(){return x;}
double gety(){return y;}
};
void display3 (CPoint &p,CPoint &t);
int main()
{
CPoint p1,p2;
cout<<"输入第一个点x,y"<<endl;
p1.input();
cout<<"输入第二个点x,y"<<endl;
p2.input();
p2.Distance1(p1); //成员函数这样调用:对象名.函数名()
display2(p2,p1); //友员函数的调用和一般函数无异(但实现中可以不同)
display3(p2,p1); //一般函数的调用
return 0;
}
void CPoint::Distance1(CPoint p) const
{
double l;
l=sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));
cout<<"两点间距离为"<<l<<endl;
}
void CPoint::input()
{
int a,b;
cin>>a>>b;
x=a;
y=b;
}
void display2 (CPoint &p,CPoint &a)
{
double l;
l=sqrt((a.x-p.x)*(a.x-p.x)+(a.y-p.y)*(a.y-p.y));
cout<<"两点间距离为"<<l<<endl;
}
void display3 (CPoint &p,CPoint &a)
{
double i,j,l;
i=a.getx()-p.getx();
j=a.gety()-p.gety();
l=sqrt(i*i+j*j);
cout<<"两点间距离为"<<l<<endl;;
}
第七周——友元函数求坐标距离
最新推荐文章于 2024-01-12 01:38:06 发布