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;}