G++ 编译错误"... is protected from within this context"而 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)编译时,我收到以下错误:

classest .cpp:在构造函数' DerivedB::DerivedB() '中:
classest .cpp:9:5:错误:' int BaseClass::x '是受保护的
int BaseClass:: x;
^class .cpp:25:32: error: within this context
std:: cout & lt; & lt;DerivedA:: x;

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

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

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

GCC bug。[class.access.base]/p5:

如果在N类中命名,成员mR点可访问,如果

  • m作为N的成员是public,或者
  • m作为N的成员是私有的,R出现在N类的成员或友元中,或者
  • m作为N的成员被保护,R出现在N类的成员或友类中,或者出现在N衍生的P类的成员中。其中m作为P的成员是public, private, protected,或者
  • 存在N的基类B,在R上可访问,mB类中命名时在R上可访问。

NDerivedA, mx, RDerivedB的构造函数。存在一个DerivedA的基类BaseClass,它可以在R上访问,并且在BaseClass类中命名的x(即BaseClass::x)可以在R上访问,因此根据第四个重点,DerivedA::x可以在R上访问。

最新更新