Home > Article > Backend Development > What impact do friend functions have on class inheritance?
Inheritance of friend functions When a subclass inherits a class with friend functions: The subclass cannot inherit the friend function. Friend functions of the parent class can access private members of the child class. Friend functions of a subclass cannot access private members of the parent class.
The influence of friend functions on class inheritance
Preface
Friends A metafunction is a special C function that can access private members of a class outside the scope of the class. When it comes to class inheritance, understanding the behavior of friend functions is crucial.
Friend Functions and Inheritance
When a subclass inherits a class that has friend functions, the following rules apply:
Practical Case
Consider the following example code:#include <iostream> class Base { friend void print(Base& b); // 父类友元函数 private: int x; }; class Derived : public Base { friend void access(Derived& d); // 子类友元函数 private: int y; }; void print(Base& b) { std::cout << b.x << std::endl; } // 父类友元函数访问私有成员 x void access(Derived& d) { std::cout << d.x << " " << d.y << std::endl; } // 子类友元函数访问私有成员 x 和 y int main() { Base b; b.x = 10; print(b); // 输出:10 Derived d; d.x = 20; d.y = 30; access(d); // 输出:20 30 print(d); // 输出:20 }In this example:
has a friend function
print(), which has access to
x private members.
has a friend function
access(), which can access the parent class private members
x.
of the subclass
Derived can be accessed by the parent class
Base friend function
print(), but cannot Access the private member
x of the parent class.
The above is the detailed content of What impact do friend functions have on class inheritance?. For more information, please follow other related articles on the PHP Chinese website!