Home  >  Article  >  Backend Development  >  Detailed explanation of C++ friend functions: What is the role of friend functions in multiple inheritance?

Detailed explanation of C++ friend functions: What is the role of friend functions in multiple inheritance?

WBOY
WBOYOriginal
2024-04-29 18:39:01851browse

Friend functions allow non-member functions to access private members and play a role in multiple inheritance, allowing derived class functions to access private members of the base class.

C++ 友元函数详解:友元函数在多继承中的作用?

C Detailed explanation of friend functions: The role of friend functions in multiple inheritance

Introduction to friend functions

A friend function is a special function that is given access to private members without requiring an object of the class. It is often used to allow non-member functions to access private data.

Syntax:

class ClassName {
    ... // 类成员
    friend FunctionName;
};

The role of friend functions in multiple inheritance

In multiple inheritance, a derived class Data members and methods can be inherited from multiple base classes. If a function in a derived class needs to access a private member of the base class, the function can be declared as a friend function.

Practical case

Suppose we have a Base class and a derived classDerived that inherits from Base :

class Base {
private:
    int data;
};

class Derived : public Base {
public:
    void printData() {
        std::cout << data << std::endl;
    }
    friend void printData2(Derived& obj);
};

Since data is a private member of Base, the printData() function in Derived There is no way to access it directly. Therefore, we declare the printData2() function as a friend function of Derived:

void printData2(Derived& obj) {
    std::cout << obj.data << std::endl;
}

Now, printData2() can access ## Private data member in #Derived.

Usage:

int main() {
    Derived obj;
    obj.printData();
    printData2(obj);
}

Output:

0
0

The above is the detailed content of Detailed explanation of C++ friend functions: What is the role of friend functions in multiple inheritance?. 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