友元函数
  • 延续C语言的结构体编程方式,直接访问类的私有成员,提高效率

  • 友元分为函数友元和类友元

    • 友元函数可以访问类的所有成员

    • 友元类的所有成员函数都是友元函数

  • 友元不具备传递性

  • 友元函数和类的成员函数的区别

    • 友元函数不是类的成员,只是声明

    • 成员函数有this指针,而友元函数没有this指针

  • 开发中不建议使用友元函数,破坏了类的封装性

函数友元例子

 #include <iostream>

 using namespace std;

 class Test
{
private:
int a; public:
Test() { a = ;} Test(int a) {this->a = a;} void show()
{
cout << "a = " << a << endl;
} friend void g_show(Test t);
}; void g_show(Test t)
{
cout << "[g_show] t.a = " << t.a << endl;
return;
} int main()
{
Test t();
t.show();
g_show(t);
return ;
}

类友元例子

 #include <iostream>

 using namespace std;

 class Test
{
private:
int a; public:
Test() { a = ;} Test(int a) {this->a = a;} friend class Friend;
}; class Friend
{
private:
Test t; public:
Friend() : t() {} void show()
{
cout << "Friend t.a = " << t.a << endl;
}
}; int main()
{
Friend f;
f.show(); return ;
}

最新文章

  1. Asp.Net:Repeater 详情 备用
  2. 完整学习git一git设置
  3. 2016-1-10 手势解锁demo的实现
  4. MySQL 5.5 服务器变量详解一(转)
  5. Unix环境编程之定时、信号与中断
  6. qsort函数、sort函数 (精心整理篇)
  7. Preparing for the Contest
  8. shell 分词
  9. UVA - 10339-Watching Watches
  10. TestNG exception
  11. 【JS】VUE学习
  12. js中return false; jquery中需要这样写:return false(); Jquery 中循环 each的用法 for循环
  13. spark-sql分组去重总数统计uv
  14. 备份原有yum源,设置为自建yum源的脚本
  15. Spring Boot + Mybatis + Redis二级缓存开发指南
  16. 用SSH登录远程的机器,在远程机器上执行本地机器上的脚本
  17. centos7之安装wordpress
  18. Redis持久化实践及灾难恢复模拟 [转]
  19. iOS刻度尺换算之1mm等于多少像素理解
  20. 关于list集合存储null的问题

热门文章

  1. OpenResty入门之使用Lua开发Nginx插件
  2. 15.DRF-分页
  3. 一个JS库Lodash
  4. vue指令,实例成员,父子组件传参
  5. Shell 脚本学习(1)
  6. Redis五种数据类型应用场景
  7. 一种基于LQR使输出更加稳定的算法(超级实用)
  8. 【错误】上传新的项目出错 error: failed to push some refs to &#39;https://github.com/...
  9. docker 运行镜像
  10. 使用Python编写的对拍程序