友元是可以访问类的私有成员和保护成员的外部函数。由 friend 修饰,不是本类的成员函数,但是在它的函数体中可以通过对象名访问本类的私有和保护成员。

    友元关系不可传递,且是单向的。

   友元函数:声明为友元的一般函数或是另一个类的成员函数;

 友元类:友元类的所有成员函数都是某个类的友元函数。应用场景较少。

 1、友元函数

应用于运算符重载多一些。

#include <iostream>
#include <cmath>
using namespace std; //友元函数举例
class Point {
public:
Point(int xx = , int yy = )
{
X = xx; Y = yy;
}
int GetX() { return X; }
int GetY() { return Y; }
friend float fDist(Point &a, Point &b);
private:
int X, Y;
};
//友元函数的实现
float fDist(Point &p1, Point &p2)
{
//通过对象访问私有数据成员
double x = double(p1.X - p2.X);
double y = double(p1.Y - p2.Y);
return float(sqrt(x*x + y*y));
}
void main()
{
Point myp1(, ), myp2(, );
cout << "The distance is: ";
cout << fDist(myp1, myp2) << endl;
system("pause");
}

2、友元类

应用较少,了解即可。

#include <iostream>
using namespace std; class A {
public:
friend class B;//在 B类中可以访问 A类 的私有成员、私有函数。 // 友元类声明的位置和 public/private 没有关系。
friend void modifyA(A *pA, int _a); //该函数是 类A 的好朋友
A(int a=, int b=)
{
this->a = a;
this->b = b;
}
int getA()
{
return this->a;
}
private:
int a, b;
}; void modifyA(A *pA, int _a)
{
pA->a = _a;
}
//友元类使用场景较少
class B
{
public:
void Set(int a)
{
Aobject.a = a;
}
void printB()
{
cout << Aobject.a << endl;
}
private:
A Aobject;
};
void main()
{
A a1(, );
cout << a1.getA() << endl;
modifyA(&a1, );
cout << a1.getA() << endl; B b1;
b1.Set();
b1.printB();
system("pause");
}

最新文章

  1. mvc上传到云虚拟机的问题解决
  2. Oracle 11g 7个压缩包说明
  3. matlab函数集锦
  4. 用JS实现回文数的精准辨别!!!
  5. 第3组UI组件:AdapterView及其子类
  6. java中小工具&mdash;&mdash;&mdash;&mdash;UUID
  7. Java内部类——局部内部类
  8. Winfrom 文本框回车进入下一个个单元格(TextBox)
  9. 数字图像处理(MATLAB版)学习笔记(1)——第1章 绪言
  10. zabbix 网络模板自动发现端口时,过滤掉某些特定规则的端口,减少item的方法
  11. oracle存储过程出现ORA-01403: 未找到数据 问题解决方法
  12. java面试中经常会被问到分布式面试题
  13. 菜鸟教程之工具使用(二)——Maven打包非规范目录结构的Web项目
  14. HDU1565_方格取数(1)
  15. loj6436【PKUSC2018】神仙的游戏
  16. CCF CSP 201503-2 数字排序
  17. 使用Node.js 搭建http服务器 http-server 模块
  18. 前端PHP入门-024-字符串函数-API查看
  19. 23SpringMvc_各种参数绑定方式-就是&lt;input那种
  20. org.springframework.beans.factory.BeanCreationException: Error creating bean with name &#39;supplierAction&#39;: Injection of resource dependencies failed; nested exception is org.springframework.beans.factor

热门文章

  1. [ kvm ] 学习笔记 2:虚拟化基础
  2. easyui datagrid 让某行复选框置灰不能选
  3. Newtonsoft.Json 方法使用()
  4. PNG压缩工具-PNGGauntlet
  5. web端自动化——unittest框架编写web测试用例
  6. vue引入iconfont报错
  7. ztree节点名称排序
  8. go零碎总结
  9. SSH无密码(密钥验证)登录的配置
  10. PHP与Memcached服务器交互的分布式实现源码分析