Как взаимодействуют спецификатор доступа к производным и дружба? - PullRequest
0 голосов
/ 21 июня 2020

Я немного запутался насчет наследования и дружбы. Рассмотрим этот пример:

    class D;
    class A
    {
    protected:
        int x = 0;
    private:
        int y = 1;
    public:
        int z = 2;
    friend class D;
    };
    
    class B :  public A
    {};
    
    class C : protected A
    {};
    
    class D
    {
    public:
        void f(B b){cout << b.x << b.y << b.z << endl;} // ok
        void f2(C c){cout << c.x << c.y << c.z << endl;} // error
    };
    
  • f(B b) просто, потому что b может получить доступ ко всем членам A, потому что class D - это friend из class A .

  • Но почему f2(C c) не компилируется? на самом деле C наследует protectedly от A, а D является другом A, так почему f компилируется, а f2 - нет? и как на это влияет спецификатор доступа к производным? Спасибо!

Результат:

In member function ‘void D::f2(C)’: ../main.cpp:34:27: error: ‘int A::x’ is protected within this context 34 | void f2(C c){cout << c.x << c.y << c.z << endl;} // error | ^ ../main.cpp:16:8: note: declared protected here 16 | int x = 0; | ^ ../main.cpp:34:34: error: ‘int A::y’ is private within this context 34 | void f2(C c){cout << c.x << c.y << c.z << endl;} // error | ^ ../main.cpp:18:8: note: declared private here 18 | int y = 1; | ^ ../main.cpp:34:41: error: ‘int A::z’ is inaccessible within this context 34 | void f2(C c){cout << c.x << c.y << c.z << endl;} // error | ^ ../main.cpp:20:8: note: declared here 20 | int z = 2; | ^

...