Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Kế thừa và Friendship trong C++: Friendship không được kế thừa


Trong C++, quan hệ friend không được kế thừa. Nếu class A là friend của Base, thì Derived (kế thừa Base) không tự động là friend của Base.

Ví dụ lỗi

#include <iostream>
using namespace std;

class Base {
protected: int x = 20;
public: friend void display();
};

class Derived : public Base {
private: int y = 30;
public: Derived() { x = 40; }
};

void display() {
    Derived d;
    cout << d.x << endl; // OK: friend của Base truy cập protected x
    cout << d.y << endl; // LỖI: y là private của Derived, display KHÔNG phải friend của Derived
}

Kết quả

error: 'int Derived::y' is private within this context