Home  >  Article  >  Backend Development  >  Detailed explanation of C++ friend functions: How to declare a friend class?

Detailed explanation of C++ friend functions: How to declare a friend class?

王林
王林Original
2024-04-28 15:00:02576browse

In C, a friend class allows all member functions of one class to access private members of another class. When declaring a friend class, use the friend class keyword, for example: OuterClass declares the inner class as a friend class: friend class inner class; only the member functions in the inner class can access the private members of OuterClass.

C++ 友元函数详解:如何声明友元类?

C Detailed explanation of friend function: How to declare a friend class

Preface

In C, friend relationships are a powerful mechanism that allows non-member functions to access private members of a class. A friend class is a special form of friend relationship that allows all member functions of one class to access the private members of another class.

Declaration of Friend Class

To declare a friend class, you need to use the friend keyword in the definition of the class. The syntax is as follows:

class OuterClass {
    // 成员变量和函数

    friend class InnerClass;
};

This will allow all member functions in InnerClass to access the private members of OuterClass, but not other classes.

Practical Case

Let us consider a practical example, where OuterClass represents a class containing sensitive data, and inner class Represents a utility class that needs to access this data.

OuterClass:

class OuterClass {
private:
    int secretData;  // 敏感数据

public:
    // 可以公开访问的数据和方法
};

Inner Class:

class InnerClass {
    friend class OuterClass;  // 声明友元类

public:
    void printData(OuterClass& outerObj) {
        // 访问OuterClass的私有成员 secretData
        cout << "敏感数据:" << outerObj.secretData << endl;
    }
};

In this case, only InnerClass# Member functions in ## can access the secretData member of OuterClass. Other classes cannot access this private member.

Note:

    Friend class is a one-way relationship.
  • OuterClass can only access the public members of inner class, while inner class can access all members of OuterClass.
  • Friend classes can be class templates or class instantiations.
  • Multiple classes can be designated as friends by using the
  • friend class* syntax in the class definition.

The above is the detailed content of Detailed explanation of C++ friend functions: How to declare a friend class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn