C++学习之友元类

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

关于友元类的注意事项:

(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_INCLUDED

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

至此,友元类使用完成。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值