gpt4 book ai didi

c++ - 在 C++ 中进行 protected 成员可访问性额外检查的原因是什么?

转载 作者:太空狗 更新时间:2023-10-29 20:42:08 25 4
gpt4 key购买 nike

我刚遇到这个问题,从 C++ 标准中知道它定义如下(强调我的)

An additional access check beyond those described earlier in Clause 11 is applied when a non-static data member or non-static member function is a protected member of its naming class (11.2)115 As described earlier, access to a protected member is granted because the reference occurs in a friend or member of some class C. If the access is to form a pointer to member (5.3.1), the nested-name-specifier shall denote C or a class derived from C. All other accesses involve a (possibly implicit) object expression (5.2.5). In this case, the class of the object expression shall be C or a class derived from C.

代码片段:

class Base
{
protected:
int i;
};

class Derived : public Base
{
public:
// I cannot define it as void memfunc(Derived* obj) because of signature requirement.
void memfunc(Base* obj)
{
obj->i = 0; // ERROR, cannot access private member via Base*
Derived* dobj = (Derived*)(obj);
dobj->i = 0; // OK
}
};

那么这个检查的原因是什么?为什么 C++ 标准费心去限制通过基类指针访问 protected 成员?

不重复:Accessing protected members in a derived class ,想问下标准禁止的原因。

最佳答案

仅仅因为您派生自 Base 并不意味着您应该被允许访问派生自 Base 的任何其他类的 protected 成员。想象一个类 Derived2 由继承自 Base 的库提供。通过这种方式,您将能够获得 Derived2 的基础对象,并在 Derived 的代码中用它做任何您想做的事情。

基本上,该标准可确保您仅修改继承的 protected 成员,而不会破坏不相关的兄弟类的完整性。

关于c++ - 在 C++ 中进行 protected 成员可访问性额外检查的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19803971/

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