首页 文章

如何在派生类中提升或降低访问修饰符会破坏C封装?

提问于
浏览
2

Granting AccessGranting Access 主题中从 The Complete Reference 学习C时,我们可以将类的成员恢复到其原始访问状态 .

Example

class Base {
public:
    int x;
};

class Derived : private Base {
public:
    Base::x; // make x public again
};

据作者说

您可以使用访问声明来恢复公共成员和受保护成员的访问权限 . 但是,您不能使用访问声明来提高或降低成员的访问状态 . 例如,在基类中声明为private的成员不能通过派生类公开 . 如果C允许这种情况发生,它将破坏其封装机制 .

我不明白它会怎么样?

1 回答

  • 0

    它在谈论using declaration .

    通过使用"using declaration",您可以将名称带入当前作用域,以便它们对您当前的代码块可见,以便它们变得易于解析,这样您就可以减少多继承期间的歧义,这样您就不必键入long说明符以便访问它们(比如使用cout而不是std :: cout的快捷方式 . )但是,它们的访问状态仍然相同(私有保持私有,公共保持公共,受保护仍受保护) .

    class Base {
        public:
        int x;
        private:
        int y;
        protected:
        int z;
    };
    
    class Derived : public Base {
    
        // Bring x,y,z into scope
        // x is still public. y is still private. z is still protected.
    
        using Base::x;
        using Base::y; // This fails to compile. Why bring something into scope when you don't have access to it?
        using Base::z;
    };
    

    上面的代码不是使用声明的令人信服的例子(因为,继承已经将名称带入范围) . 它在其他情况下变得更有用(例如多重继承或当你尝试带一个离你当前范围很远的名字时(比如创建一个快捷名称) .

    namespace X {
        namespace Y {
           namespace Z {
              namexpace W {
                  int deep_x;
                  int deep_y;
              }
           }
        }
     }
    
    int main()
    {
         cout << X::Y::Z::W::deep_x;
         // Bringing X::Y::Z::W::deep_y into scope
         using X::Y::Z::W::deep_y;
         cout << deep_y;
    }
    

相关问题