[C++ Basics: 21]: friend Friends ask four questions: What is a friend? Friend class? Friend function? When to use friends?

This series of C++ related articles is only for the author’s study notes, and I will use my own understanding to record the study! The C++ learning series will be divided into three stages: basics, STL, and advanced data structures and algorithms . The relevant key contents are as follows:

  1. Basics : Classes and Objects (involving the three major features of C++, etc.);
  2. STL : Learn to use the STL related libraries provided by C++ ;
  3. High-order data structures and algorithms : Manually implement your own STL library and design and implement high-order data structures , such as B-tree, B+ tree, red-black tree, etc.

Study set:


Contents of this issue: [C++ Basics: 21]: Four consecutive questions about friends: What is a friend? Friend class? Friend function? When to use friends?


Contents:
1. Basic understanding of friends
2. Friend functions
- - 2.1 Basic usage of friend functions
- - 2.2 How to write the overloaded structure of cout / cin
- - 2.3 Points to note when using friend functions
3. Friend classes
- - 3.1 Basic understanding of friend classes
- - 3.2 Example + Illustration: Explaining friend classes
4. When to use friends?
5. Recommended related articles


[ C++ learning collection link ]


1. Basic understanding of friends

Friends provide a way to break through encapsulation and sometimes provide convenience. However, friends will increase coupling and destroy encapsulation, so friends should not be used more than once.


Friends are divided into: friend functions and friend classes ; keywords when declaring: friend


2. Friend function

2.1 Basic usage scenarios of friend functions

  • Mostly used to implement "stream input/stream output" and overload cout/cin .

During the process of overloading cout/cin, if the overloading is inside the class, the first parameter in the class will be this pointer by default. After overloading, this pointer will be used as the left operand, which is different from the actual cout/cin usage. To violate!

In fact, the first parameter of cout / cin should be a formal parameter object! Therefore, the corresponding overload cannot be declared and defined inside the class ! The solution is to declare it as a global function ;
but the next problem is: member variables in the class cannot be accessed outside the class ! [At this time, Youyuan played a very good role!


2.2 How to write the overloaded structure of cout / cin

The overloaded structure of cout / cin is written as follows: [Note: Due to the high frequency of use, it is usually declared as an inline function] (I will talk about it later, just understand it here)

// xxx.h
class A{
public:
    friend ostream& operator << (ostream& _cout, const A& a);
    friend istream& operator >> (istream& _cin, A& a);
};

inline ostream& operator<< (ostream& _cout, const A& a){
    _cout << ... << ... << ...;
    return _cout;
}
inline istream& operator>> (istream& _cin, A& a){
    _cin >> ... >> ... >> ...;
    return _cin;
}

2.3 Points to note when using friend functions

A friend function can directly access the private members of a class. It is an ordinary function defined outside the class and does not belong to any class. However, it needs to be declared inside the class. The friend keyword needs to be added when declaring.


  1. Friend functions have access to private and protected members of a class, but not to member functions of the class.
  2. Friend functions cannot be modified with const.
  3. Friend functions can be declared anywhere in a class definition and are not restricted by class access qualifiers.
  4. A function can be a friend function of multiple classes.
  5. The principle of calling friend functions is the same as that of ordinary functions.

3. Friend class

3.1 Basic understanding of friend classes

All member functions of a friend class can be friend functions of another class and can access non-public members of another class.

  • Friend relationships are one-way and non-commutative. [For example, Time class and Date class, declare the Date class as its friend class in the Time class, then you can directly access the private member variables of the Time class in the Date class, but you want to access the private member variables of the Date class in the Time class No.
  • Friend relationships cannot be transitive [If C is a friend of B and B is a friend of A, it cannot mean that C is a friend of A]
  • Friend relationships cannot be inherited . I will give you a detailed introduction to the inheritance position.

3.2 Example + Illustration: Explaining Friend Classes

The picture is behind the code!

#include<iostream>
using std::cout;
using std::endl;

class Time
{
    friend class Date;      // 声明日期类为时间类的友元类,则在日期类中就直接访问Time类中的私有成员变量
public:
    Time(int hour = 0, int minute = 0, int second = 0)
        : _hour(hour)
        , _minute(minute)
        , _second(second)
    {}
private:
    int _hour;
    int _minute;
    int _second;
    void PrintTime() {
        cout << _hour << ":" << _minute << ":" << _second << endl;
    }
};
class Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)
        : _year(year)
        , _month(month)
        , _day(day)
    {}
    void SetTimeOfDate(int hour, int minute, int second)
    {
        // 直接访问时间类私有的成员变量
        _t._hour = hour;
        _t._minute = minute;
        _t._second = second;
    }
    void PrintTime() {  
        _t.PrintTime();         // 直接访问 Time 类的成员函数
    }
private:
    int _year;
    int _month;
    int _day;
    Time _t;
};


int main() {
    // 直接构造一个默认的日期类
    Date d1;

    d1.PrintTime();

    d1.SetTimeOfDate(22, 21, 20);

    d1.PrintTime();

    return 0;
}

Insert image description here

Note: If it is not a friend relationship, the above form can only access public members! That is, there is no calling relationship in the figure and an error is reported directly!

Insert image description here


4. When to use friends?

Recall what a friend is and what is its function? : Friends provide a way to break through encapsulation, sometimes providing convenience. However, friends will increase coupling and destroy encapsulation, so friends should not be used more than once.


A brief summary of the above examples of friend functions and friend classes:

  1. When you need to overload stream input/stream output! (cout/cin);
  2. Used when a class needs to access member variables of another class with a certain relationship. [To put it bluntly, it is used when you want to break through the limitations of class encapsulation]

5. Recommended related articles

1. C++ learning:: [Basics: 05]: Understanding and using C++ function overloading, a brief introduction: the reasons why C++ supports function overloading 2. C++
learning:: [Basics: 09]: Understanding and basics of C++ classes Declaration definition; a simple comparison of the difference between classes and structures in C++
3. C++ learning:: [Basics: 10]: Introduction and explanation of access qualifiers of C++ classes (three types) and class encapsulation (one of the three major features) Preliminary understanding
4. C++ learning:: [Basics: 11]: Basic use of C++ classes and non-static this pointers (two interview test points): The null pointer problem of classes (can this pointer be null?) | This pointer exists where?

Guess you like

Origin blog.csdn.net/weixin_53202576/article/details/131037673