【问题标题】:How raising or lowering access modifier in derived class destroys C++ encapsulation?在派生类中提高或降低访问修饰符如何破坏 C++ 封装?
【发布时间】:2017-02-02 15:58:40
【问题描述】:

继承Granting Access主题中从The Complete Reference学习C++时,写到我们可以恢复类的成员恢复到原来的访问状态。

示例

class Base {
public:
    int x;
};

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

据作者介绍

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

我不明白这将如何发生?

【问题讨论】:

  • 您需要引用完整的上下文。 We can not raise or lower the access status of a member 这通常是不正确的。例如,使用受保护或公共继承的类可以将基类的受保护成员公开。
  • 我添加了完整的段落@dxiv
  • x 已在Base 中公开...您还缺少using 吗?
  • @newbee 你确定这是完整的段落吗? You can use an access declaration to restore the access rights of public and protected member. However,you can not use an access declaration to raise or lower the access status of a member. 除非您将 member 更改为 private member,否则第二句与第一句相矛盾。
  • 这很不幸。访问声明已被弃用,本书根本不应该讨论它们,除非在脚注中。考虑再买一本书。

标签: c++


【解决方案1】:

它在谈论using declaration

通过使用“使用声明”,您可以将名称带入当前范围,以便它们对您当前的代码块可见,以便它们易于解析,从而可以减少多重继承期间的歧义,以便您不必输入长说明符来访问它们(例如使用 cout 而不是 std::cout 的捷径。)但是,它们的访问状态仍然保持不变(private 仍然是 private,public 仍然是 public,protected 仍然是受保护的)。

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2011-06-13
    • 2017-03-28
    • 2016-06-10
    • 1970-01-01
    • 2018-03-06
    相关资源
    最近更新 更多