Home > Backend Development > C++ > body text

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

WBOY
Release: 2024-04-29 18:39:01
Original
875 people have browsed it

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;
};
Copy after login

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);
};
Copy after login

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;
}
Copy after login

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

Usage:

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

Output:

0
0
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!