Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Inheritance และ Friendship ใน C++

Friendship ใน C++ ไม่ถูกสืบทอด (not inherited) หาก Base class มี friend function Derived class จะไม่ได้รับสิทธิ์ friend นั้น

ตัวอย่าง Error

class Base {
protected: int x;
public: Base() : x(20) {}
friend void display(); // friend ของ Base
};

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

void display() {
    Derived d;
    cout << d.x; // OK: x เป็น protected ของ Base
    cout << d.y; // ERROR: y เป็น private ของ Derived, display ไม่ใช่ friend ของ Derived
}

ผลลัพธ์

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

Friendship เป็นความสัมพันธ์แบบ one-way และไม่สืบทอด ต้องระวังในการออกแบบคลาส