由C++的友元类延伸出来的类的封装特性

 大家好,今天给大家分享一个C++的友元类的知识点,重点不是友元类,因为它不常用,它是C++类的封装的一个补充,其实它破坏了类的封装特性。下面直接以代码说明问题。

//Time.h
#ifndef TIME_H
#define TIME_H
class Match;
class Time
{
      public:
            // friend class Match;
             Time(int hour,int min,int sec);//先通过构造函数初始化成员函数
             
       private:
              void printTime();
              int m_iHour;
              int m_iMinute;
              int m_iSecond;
              };
 #endif 
      

  首先,新建一个控制台工程,声明Time这个头文件(上面的代码),然后实现头文件,

//Time.cpp

#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.h

#ifndef MATCH_H
#define MATCH_H
#include "Time.h"
class Match
{
      public:
             Match(int hour,int min,int sec);
             void testTime();
             int a;
      private:
              Time m_tTimer;
            
              };
#endif
//Match.cpp
#include "Match.h"
#include <iostream>
using namespace std;

Match::Match(int hour,int min,int sec):m_tTimer(hour,min,sec)
{
}
void Match::testTime()
{
      m_tTimer.printTime();
      cout<<m_tTimer.m_iHour<<":"<<m_tTimer.m_iMinute<<":"<<m_tTimer.m_iSecond<<endl;
     }    

最后是Demo主函数代码:

#include "Time.h"
#include "Match.h"
#include "stdlib.h"
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{   
    Match m(17,33,30);
    m.testTime();
    m.a = 6;
    cout<<m.a<<endl;
    system("PAUSE");
    return 0;
}

上述代码我把friend class Match 注释掉以后会报错,

取消注释,则运行成功,说明如果不是友元类的A类的成员函数访问另一个类B的成员和成员函数时,只能通过B的对象访问到B类里面的共有成员,和共有成员函数,或者通过B类的公有成员函数,来访问B类的私有成员,这个符合类的封装的特性。如果A为B的友元类,则一切皆可访问,从而破坏了类的封装性。

猜你喜欢

转载自www.cnblogs.com/yerhu/p/11488781.html