/*
*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;
}
运行结果: