Package Characteristics friend class extending out of the C ++ class

 Hello everyone, today to share a knowledge of C ++ friend classes, the focus is not the friend class, because it is not commonly used, it is a complementary package of C ++ classes, in fact, it undermines the package attribute class. The following code illustrates the problem directly.

//Time.h 
#ifndef TIME_H 
#define TIME_H 
class Match; 
class Time 
{ 
      public: 
            // class Friend Match; 
             Time (hour int, int min, int sec); // constructor initializes via the first member function 
             
       Private: 
              void printTime (); 
              int m_iHour; 
              int m_iMinute; 
              int m_iSecond; 
              }; 
 #endif
      

  First, create a new console project, the header file declarations Time (the code above), then realize the header file,

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

Statement Match.h and implement it, the code is as follows; // 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;
     }    

Finally Demo main function codes:

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

The code I put the friend class Match will complain later commented,

 

Uncommented, then run successfully, indicating that if not a friend class member functions Class A members and member functions to access another class B, and can only be accessed with a total membership to Class B via the inside of the object B, and the total of member functions or by the public member functions of the class B, to access the private members of class B, for which the package in line with the characteristics of the class. If A is a friend class B, then all universally accessible, thus destroying the package of the class.

Guess you like

Origin www.cnblogs.com/yerhu/p/11488781.html