如解释的那样,不允许在派生类中调用 protected 构造函数 here .
接受的答案解释说 protected
仅当 A
类的对象是B
类的子对象。到目前为止,还不错。
但是,为什么允许(至少在 GCC 4.6.3 中)调用静态保护方法?具体来说,以下编译对我来说没有任何意义,而注释行则没有:
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
类对象的静态方法,这就是我在这里看不到行为差异的原因。
最佳答案
But then, why is it allowed (at least in GCC 4.6.3) to call static protected methods?
因为标准就是这么说的。适用于 protected
成员可访问性的约束(以及您链接的答案解释得很好)在 C++11 标准的第 11.4/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). [...]
附加访问检查不适用于静态成员或静态成员函数。
关于c++ - 为什么允许在派生类中调用 protected 静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16913451/