gpt4 book ai didi

c++ - 提高或降低派生类中的访问修饰符如何破坏 C++ 封装?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:45:27 27 4
gpt4 key购买 nike

The Complete Reference学习C++时,在Granting Access of Inheritance的主题中写到我们可以恢复一个类的成员到他们的原始访问状态。

示例

class Base {
public:
int x;
};

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

根据作者

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. For example a member declared as private in base class can't be made public by derived class. If C++ allows this to occur , it would destroy its encapsulation mechanism.

我不明白它会如何发生?

最佳答案

它正在谈论 using declaration .

通过使用“using declaration”,您可以将名称引入当前作用域,以便它们对您当前的代码块可见,以便它们变得易于解析,以便您可以减少多重继承期间的歧义,以便您不必键入长说明符即可访问它们(例如使用 cout 而不是 std::cout 的快捷方式)。但是,它们的访问状态仍然保持不变(私有(private)仍然是私有(private)的,公共(public)仍然是公共(public)的, protected 仍然是 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;
}

关于c++ - 提高或降低派生类中的访问修饰符如何破坏 C++ 封装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39683669/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com