#include "math.h"
#include<iostream>
using namespace std;
class Point
{
public:
Point(double xx, double yy)
{
x=xx;
y=yy;
}
void Getxy();
friend double Distance(Point &a, Point &b); //类Point的友元函数
friend class Yao; //类Point的友元类
private:
double x, y;
};
class Yao
{
public:
double Multi(Point &a)
{
return a.x * a.y + 1;
}
};
void Point::Getxy()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
double Distance(Point &a, Point &b) //类Point的友元函数
{
double dx = a.x - b.x;
double dy = a.y - b.y;
return sqrt(dx*dx+dy*dy);
}
int main(void)
{
Point p1(3.0, 4.0), p2(6.0, 8.0);
p1.Getxy();
p2.Getxy();
double d = Distance(p1, p2); //Distance是类Point的友元函数,不是成员函数
cout<<"Distance is "<<d<<endl;
Yao yao;
d = yao.Multi(p1);
cout<<"Math.Multi is "<<d<<endl;
return true;
}
友元的使用并不复杂,且缺了这玩意完全可以实现,但既然这么设计,就有它存在的合理性,在某些条件下使用它还是很方便的。另外需要注意的一点,编程时,滥用这个东西容易引起数据的安全问题,故需谨慎使用之。
原文链接: https://www.cnblogs.com/Roarsun/archive/2012/12/22/2829088.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/73231
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!