gpt4 book ai didi

c++ - 访问基类的 protected 构造函数

转载 作者:可可西里 更新时间:2023-11-01 16:21:10 24 4
gpt4 key购买 nike

派生类可以在其ctor-initializer 中调用 protected 基类构造函数,但仅限于其自己的基类子对象,而不能在其他地方调用:

class Base {
protected:
Base() {}
};

class Derived : Base {
Base b;
public:
Derived(): Base(), // OK
b() { // error
Base b2; // error
}
};

标准对此有何规定?这是 [class.protected]/1:

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) 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. [ Example: ...

调用构造函数时是否涉及对象表达式?没有,是吗?那么标准中哪里描述了 protected 基类构造函数的访问控制?

最佳答案

protected 访问仅适用于您自己的当前对象类型 的父成员。您不能公开访问父类型的其他 对象的 protected 成员。在您的示例中,您只能访问默认基础构造函数作为 Derived 的一部分,而不是当它是作为 b 的独立对象时。

让我们分解一下您发布的标准 (11.4/1) 中的引述。我们假设标准中的 C 对应于您的 Derived 类:

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).

所以基类构造函数在这里实际上是它的命名类 (B) 的一个非静态成员函数,所以这个条款到目前为止适用。

As described earlier, access to a protected member is granted because the reference occurs in a friend or member of some class C.

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.

最后,标准声明表达式的类必须是 C 或更进一步的派生类。在这种情况下,您的表达式 Base() 实际上是一个 C,调用父构造函数(将其视为 this->Base() . 表达式 b 显然是 Base 类型(这是成员 b 的显式声明类型,想想 this->b ->Base())。现在我们检查:BaseC 还是 C 的子级?不是, 所以这个代码是不合法的。

关于c++ - 访问基类的 protected 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24636234/

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