C++语法小记---友元
2024-10-09 08:26:17
友元函数
延续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 ;
}
最新文章
- Asp.Net:Repeater 详情 备用
- 完整学习git一git设置
- 2016-1-10 手势解锁demo的实现
- MySQL 5.5 服务器变量详解一(转)
- Unix环境编程之定时、信号与中断
- qsort函数、sort函数 (精心整理篇)
- Preparing for the Contest
- shell 分词
- UVA - 10339-Watching Watches
- TestNG exception
- 【JS】VUE学习
- js中return false; jquery中需要这样写:return false(); Jquery 中循环 each的用法 for循环
- spark-sql分组去重总数统计uv
- 备份原有yum源,设置为自建yum源的脚本
- Spring Boot + Mybatis + Redis二级缓存开发指南
- 用SSH登录远程的机器,在远程机器上执行本地机器上的脚本
- centos7之安装wordpress
- Redis持久化实践及灾难恢复模拟 [转]
- iOS刻度尺换算之1mm等于多少像素理解
- 关于list集合存储null的问题
热门文章
- OpenResty入门之使用Lua开发Nginx插件
- 15.DRF-分页
- 一个JS库Lodash
- vue指令,实例成员,父子组件传参
- Shell 脚本学习(1)
- Redis五种数据类型应用场景
- 一种基于LQR使输出更加稳定的算法(超级实用)
- 【错误】上传新的项目出错 error: failed to push some refs to &#39;https://github.com/...
- docker 运行镜像
- 使用Python编写的对拍程序