派生类中的静态方法可以在C++中调用受保护的构造函数吗?

Joh*_*nck 21 c++ static constructor compiler-errors protected

这段代码适用于clang,但g ++说:

错误:'A :: A()'受到保护

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

class B : public A
{
    static A f() { return A(); } // GCC claims this is an error
};
Run Code Online (Sandbox Code Playgroud)

哪个编译器是对的?

Kir*_*sky 11

g ++是对的.

C++标准§11.5/ 1表示"<...>访问必须通过指向,引用或派生类本身的对象<...>".对于构造函数,这意味着B只允许调用受保护的构造函数A以构造自己的基础子对象.

用g ++ 检查这个相关的问题.它被关闭不是一个错误.

  • +1至于基本原理,`protected`提供对'B`里面`A`子对象的访问,而不是*any*`A`.另一个例子是`struct C:A {static void break_invariants(B&b){b.protected_member_from_A = 5; `*,它可能*可能*打破`B`中保存的不变量. (2认同)