C++学习之友元类

来源:互联网 发布:java类修饰符 编辑:程序博客网 时间:2024/06/06 01:45

友元类的所有成员函数都是另一个类的友元函数,都可以访问另一个类中的隐藏信息(包括私有成员和保护成员)。当希望一个类可以存取另一个类的私有成员时,可以将该类声明为另一类的友元类。

关于友元类的注意事项:

(1) 友元关系不能被继承。
(2) 友元关系是单向的,不具有交换性。若类B是类A的友元,类A不一定是类B的友元,要看在类中是否有相应的声明。
(3) 友元关系不具有传递性。若类B是类A的友元,类C是B的友元,类C不一定是类A的友元,同样要看类中是否有相应的申明。
(4) 友元声明的形式及数量不受限制。
重要一点:友元只是封装的补充,破坏了类的封装性
接下来看一下编程实例,跟上篇友元函数的实例差不多
定义两个类time和match

time.h

#ifndef TIME_H_INCLUDED#define TIME_H_INCLUDEDclass match;//需要先声明一下这个类class time{    friend match;//声明友元类public:    time(int hour,int min,int sec );private:    void printTime();    int m_iHour;    int m_iMinute;    int m_iSecond;};#endif // TIME_H_INCLUDED

time.cpp
在这里,定义time类成员函数的定义

#include<iostream>#include"time.h"using namespace std;time::time(int hour,int min,int sec){    m_iHour=hour;    m_iMinute=min;    m_iSecond=sec;}void time::printTime(){    cout<<m_iHour<<"时"<<m_iMinute<<"分"<<m_iSecond<<"秒"<<endl;}

match.h
match类的定义

#ifndef MATCH_H_INCLUDED#define MATCH_H_INCLUDED#include"time.h"class match{public:  match(int hour,int min,int sec);  void testTime();private:    time m_tTimer;定义私有数据成员m_tTimer};#endif // MATCH_H_INCLUDED

match.cpp
在这里定义类的成员函数

#include"match.h"#include<iostream>using namespace std;match::match(int hour,int min,int sec):m_tTimer(hour,min,sec)//通过初始化列表,实例化match,m_tTimer的参数也会被实例化{}void match::testTime(){    m_tTimer.printTime();//调用time类的私有成员函数    cout<<m_tTimer.m_iHour<<":"<<m_tTimer.m_iMinute<<":"<<m_tTimer.m_iSecond<<endl;//调用time类私有成员的值}

主函数main.cpp

#include <iostream>#include "match.h"#include "time.h"#include "stdlib.h"using namespace std;int main(){    match m(6,30,56);    m.testTime();    cout << "Hello world!" << endl;    return 0;}

至此,友元类使用完成。

原创粉丝点击