g++ 编译错误“... is protected from within this context”,而 clang 没有错误

g++ compilation error "... is protected from within this context" while there's no error with clang

我有以下代码:

#include <iostream>

class BaseClass {
 protected:
 static int x;
};

int BaseClass::x;

class DerivedA: public BaseClass {
 public:
     DerivedA() {
        x = 3;
     }
};    

class DerivedB: public BaseClass {
 public:
     DerivedB() {
        std::cout << DerivedA::x;
     }
};

int main(int argc, char* argv[]) {
        DerivedB b;
}

使用 g++ 编译 (g++ classtest.cpp) 我收到以下错误:

classtest.cpp: In constructor ‘DerivedB::DerivedB()’:
classtest.cpp:9:5: error: ‘int BaseClass::x’ is protected
int BaseClass::x;
^ classtest.cpp:25:32: error: within this context
std::cout << DerivedA::x;

当我用 clang++ (clang++ classtest.cpp) 编译时没有错误。

为什么 g++ 返回编译错误?

我使用 g++ 5.1.0 版和 clang++ 3.6.1 版

海湾合作委员会错误。 [class.access.base]/p5:

A member m is accessible at the point R when named in class N if

  • m as a member of N is public, or
  • m as a member of N is private, and R occurs in a member or friend of class N, or
  • m as a member of N is protected, and R occurs in a member or friend of class N, or in a member of a class P derived from N, where m as a member of P is public, private, or protected, or
  • there exists a base class B of N that is accessible at R, and m is accessible at R when named in class B.

NDerivedAmxRDerivedB的构造函数。存在 DerivedA 的基 class BaseClass 可在 R 访问,并且 x 在 class BaseClass 中命名(即, BaseClass::x) 显然可以在 R 访问,因此根据第四个要点,DerivedA::x 可以在 R.

访问