28.友元

1.友元是C++中的一种关系
2.友元关系发生在函数与类之间或者类与类之间
3.友元是单向,不能传递

用法:
        1.friend关键字声明
        2.类的友元可以是其他类或者具体函数
        3.友元不是类的一部分
        4.友元不受类中的访问级别的限制
        5.友元可以直接访问具体类中的所有成员(包括private的成员)

#include <iostream>
using namespace std;

class Point
{
private:
    double x;
    double y;

public:
    Point(double x, double y)
    {
        this->x = x;
        this->y = y;
    }

    double getX()
    {
        return x;
    }

    double getY()
    {
        return y;
    }

    friend double func(Point &p1, Point &p2);
};

double func(Point &p1, Point &p2)
{
    double ret = 0;
    
    ret = (p2.y - p1.y)*(p2.y - p1.y) +
        (p2.x - p1.x)*(p2.x - p1.x);
    ret = sqrt(ret);

    return ret;
}

int main()
{
    Point p1(1, 2);
    Point p2(10, 20);
    cout << "p1 = " << p1.getX() << " " << p1.getY() << endl;
    cout << "p2 = " << p2.getX() << " " << p2.getY() << endl;

    cout << "|p2 - p1| = " << func(p1, p2) << endl;

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/kenantongxue/p/10751363.html