一般函数:
#include
#include
using namespace std;
class Point
{
public:
Point(double a, double b);
double Getx(){return x;};
double Gety(){return y;};
private:
double x;
double y;
};
Point::Point(double a, double b)
{
x = a;
y = b;
}
double distance(double a,double b,double c,double d)
{
return sqrt((a-c)(a-c) + (b-d)(b-d));
}
int main()
{
double x1, y1, x2, y2,dist;
double a,b,c,d;
cout << “Please enter the coordinates of the first point” << endl;
cin >> x1 >> y1;
cout << “Please enter the coordinates of the second point” << endl;
cin >> x2 >> y2;
Point first(x1, y1),second(x2, y2);
a=first.Getx();b=first.Gety();
c=second.Getx();d=second.Gety();
dist =distance(a,b,c,d);
cout << “Distance=” << dist << endl;
return 0;
}
友元函数:
#include
#include
using namespace std;
class Point
{
public:
Point(double a = 0, double b = 0) :x(a), y(b){}
double getx(){ return x; }
double gety(){ return y; }
private:
double x;
double y;
friend double Distance(Point& first, Point& second);
};
double Distance(Point& first, Point& second)
{
return sqrt((first.x - second.x)(first.x - second.x) + (first.y - second.y)(first.y - second.y));
}
int main()
{
double x1, y1, x2, y2;
cout << “Please enter the coordinates of the first point” << endl;
cin >> x1 >> y1;
cout << “Please enter the coordinates of the second point” << endl;
cin >> x2 >> y2;
Point first(x1, y1),second(x2, y2);
cout << “The coordinates of the first point:(” << first.getx() << “,” << first.gety() << “)” << endl;
cout << “The coordinates of the second point:(” << second.getx() << “,” << second.gety() << “)” << endl;
cout << “Distance=” << Distance(first, second) << endl;
return 0;
}
两种方法:友元函数和一般函数 定义一个Point类,求两点之间的距离。
最新推荐文章于 2023-08-22 10:16:13 发布