为什么允许在派生类中调用受保护的静态方法? [英] Why calling a protected static method in derived classes is allowed?

查看:117
本文介绍了为什么允许在派生类中调用受保护的静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不允许在派生类中调用受保护的构造函数,如此处所述。 。

Invoking a protected constructor in a derived class is not allowed, as explained here.

接受的答案解释了 protected 授予对基类对象 A 仅当类 A 的对象是类 B 的子对象时。到目前为止,这么好。

The accepted answer explains that protected grants access to members of an object of base class A only when that object of class A is a subobject of class B. So far, so good.

但是,为什么允许(至少在GCC 4.6.3中)调用静态保护方法?具体来说,对我来说以下编译没有任何意义,而注释行没有:

But then, why is it allowed (at least in GCC 4.6.3) to call static protected methods? Specifically, it doesn't make any sense to me that the following compiles, while the commented line does not:

class A 
{
protected:
    A() {}
    static A makeA() { return A(); }
};

class B: public A
{
public:
    static A makeAFromB()
    {
        return makeA(); // compiles
        // return A();  // does not compile
    }
};

哲学上,构造函数非常类似于返回类 A ,这是我在这里没有得到行为差异的原因。

Philosophically, a constructor is pretty much like a static method returning an object of class A, reason why I don't get the difference in behaviour here.

推荐答案


但是,为什么允许(至少在GCC 4.6.3中)调用静态保护方法?

But then, why is it allowed (at least in GCC 4.6.3) to call static protected methods?

因为这就是标准所说的。适用于 protected 成员的可访问性的约束(以及您所链接的答案解释得非常好)在C ++ 11标准的第11.4 / 1节中定义,第一句指定:

Because that's what the Standard says. The constraints that apply to the accessibility of protected members (and that the answer you linked explains very well) are defined in paragraph 11.4/1 of the C++11 Standard, whose first sentence specifies:


非静态 data
member或非静态成员函数是其命名类的受保护成员(11.2)。 [...]

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

附加访问权限检查不适用于静态成员或静态成员函数。

The additional access check does not apply to static members or static member functions.

这篇关于为什么允许在派生类中调用受保护的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆