c++之友元类
来源:互联网 发布:默纳克刷机软件 编辑:程序博客网 时间:2024/06/09 14:50
友元类的作用
假设A为B 的友元类,那么可以在A中的private中定义一个B的对象C,并且可以在A中的函数中直接通过c访问B的私有成员或函数,而不需要往这个函数传递参数
注意事项
1.友元关系不可以传递
2.友元关系的单向性,即一定要搞清楚谁是谁的友元类
3.友元类的数量是不受限制的。
4.需要知道的是,友元的试用破坏了封装性。
代码演示
time.h
#ifndef TIME_H#define TIME_Hclass match;//这里必须要有match的声明,否则后面使用friend match他会不知道match是啥class Time{friend match;//可知match为time的友元类。注意结构是friend+类名,不是friend + class +类名public: Time();private: void printTime(); int m_ihour; int m_iminute; int m_isecond;};#endif // TIME_H
time.cpp
#include <iostream>#include "time.h"using namespace std;Time::Time(){ m_ihour = 6; m_iminute =30; m_isecond =50;}void Time::printTime(){ cout << m_ihour <<"shi" << m_iminute << "fen"<<m_isecond <<"miao"<<endl;}
match.h
#ifndef MATCH_H#define MATCH_H#include "time.h"class match{public: match(); void testtime();private: Time m_tTimer;//在友元类中声明对象要在private中};#endif // MATCH_H
match.cpp
#include <iostream>#include "match.h"using namespace std;match::match(){}void match::testtime()//注意,这里不需要将m_tTimer作为参数传递进来,因为前面说了友元就是直接访问。如果传递了参数,那就是前面学的友元函数(讲一个类传递进来),而不是友元类了。{ m_tTimer.printTime();//这里体现的是访问函数 cout << m_tTimer.m_ihour <<":" <<m_tTimer.m_iminute << ":"<<m_tTimer.m_isecond <<endl;//这里体现的是访问私有数据成员}
main.cpp
#include <iostream>#include "match.h"#include "time.h"using namespace std;int main(){ match m; m.testtime(); return 0;}
阅读全文
0 0
- C语言之认识C
- C语言之四书五经
- C语言之四书五经
- C语言之四书五经
- C语言之数据类型
- C语言之指针
- 正则表达式之C#
- C语言之解析
- .net学习之c#
- c#之路
- C语言之诡异
- C#、Java之比较
- 学习笔记之c
- C语言之四书五经
- C程序设计之四书五经
- C语言之指针
- C#、Java之比较
- C之诡谲
- 用CSS给图片设置大小
- MultiSelect使用!
- TCP的三次握手(建立连接)和四次挥手(关闭连接)
- 关于XE8开发安卓手机硬件
- 自定义Quartz超实用工具类
- c++之友元类
- 使用ajax后获取元素的方法以及事件委托的使用
- leetcode 154. Find Minimum in Rotated Sorted Array II(二分+递归)
- js 表格查询+升序降序+敏感词
- 在pcl用例中获取kinect深度图像数据,并用opencv显示出来
- LeetCode--Minimum Path Sum (最小路径和)Python
- C++ 递归实现简单语言解释器
- “懂你”才叫人工智能 根本不用担心AI抢你饭碗
- 表单只读不能编辑