程序员C++

实验三

2018-05-27  本文已影响11人  修夏之夏i

编写程序,定义一个平面点“Point”类及计算两点之间距离“Distance”类,
将“Distance”类定义为“Point”类的友元类;
并在main()中计算任意两点的距离。

#include<string.h>
#include<iostream>
#include<math.h>
using namespace std;

//友元类是指一个类可以作为另一个类的友元。
//可以用友元类的成员函数访问类中的成员。
class Point;
class Distance{
public:
    double distance(Point &p1,Point &p2);
};

class Point{
private:
    double x;
    double y;
public:
    Point(double a, double b) :x(a), y(b)
    {}
    friend class Distance;
};

double Distance::distance(Point &p1, Point &p2)
{
    double ret = sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));
    return ret;
}

int main()
{
    double x1, x2, y1, y2;
    cout << "x1="; cin >> x1;
    cout << "y1="; cin >> y1;
    cout << "x2="; cin >> x2;
    cout << "y2="; cin >> y2;
    Point p1(x1,y1), p2(x2,y2);
    Distance d;
    cout << "distance=" << d.distance(p1,p2) << endl;
    return 0;
}

运行结果: point.png

总结:
友元类是指一个类可以作为另一个类的友元。
将友元类定义为公有成员,可以用友元类的成员函数访问原类和友元类中的成员。

友元类中所有的成员函数为原类的友元成员函数,形参原类对象的引用。
调用友元成员函数,实参是原类的对象。

上一篇 下一篇

猜你喜欢

热点阅读