c++ - 为什么允许在派生类中调用 protected 静态方法?

标签 c++ inheritance

如解释的那样,不允许在派生类中调用 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/

相关文章:

c++ - 在 Windows 控制台中显示 unicode 棋子

c++ - 将指针 vector 存储在文件中并再次读取它们

Java 更改类的一个实例的属性也会更改另一个实例

c++ - 函数模板特化失败

java - 使用 DiscriminatorColumn 和 'wild' DiscriminatorValue 进行 JPA 实体继承

c++ - 那么现在 struct 可以有虚函数并支持继承吗?那么与 classes 有什么区别呢?信息隐藏的真正目的是什么?

c++ - 在 C++ 中,是否可以检测线程的意外终止?

c++ - 在空指针的情况下,shared_ptr 和 unique_ptr 的删除器的标准行为是否不同?

python - python 单元测试的基本测试用例类

java - 如何对车辆进行分类——继承与接口(interface)