#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 Distance1(CPoint p) const;
friend void Distance2(CPoint &, CPoint &); //友元函数声明
double getX(){return x;}
double getY(){return y;}
};
void Distance3(CPoint &, CPoint &); //一般函数声明
//用成员函数输出两点之间的距离
void CPoint :: Distance1(CPoint p) const // 两点之间的距离(一点是当前点,另一点为参数p)
{
double d;
d = sqrt((p.x - x) * (p.x - x) + (p.y - y) * (p.y - y));
cout << "用成员函数输出" << "两点之间的距离:" << d << endl;
}
//用友元函数输出两点之间的距离
void Distance2(CPoint &X, CPoint &Y)
{
double d;
d = sqrt((X.x - Y.x) * (X.x - Y.x) + (X.y - Y.y) * (X.y - Y.y));
cout << "用友元函数输出" << "两点之间的距离:" << d << endl;
}
//用普通函数输出两点之间的距离
void Distance3(CPoint &a1, CPoint &a2)
{
double d;
d = sqrt((a1.getX() - a2.getX()) * (a1.getX() - a2.getX()) + (a1.getY() - a2.getY()) * (a1.getY() - a2.getY()));
cout << "用普通函数输出" << "两点之间的距离:" << d << endl;
}
int main()
{
CPoint c1(21, 2);
CPoint c2(5, 18);
c1.Distance1(c2);
Distance2(c1, c2);//调用Distance函数,实参c1,c2是CPoint类对象。
Distance3(c1, c2);
system("pause");
return 0;
}
第七周作业2
最新推荐文章于 2023-05-03 17:12:59 发布