我有以下代码:
#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
类中命名,成员m
在R
点可访问,如果
m
作为N
的成员是public,或者m
作为N
的成员是私有的,R
出现在N
类的成员或友元中,或者m
作为N
的成员被保护,R
出现在N
类的成员或友类中,或者出现在N
衍生的P
类的成员中。其中m
作为P
的成员是public, private, protected,或者- 存在
N
的基类B
,在R
上可访问,m
在B
类中命名时在R
上可访问。
N
为DerivedA
, m
为x
, R
为DerivedB
的构造函数。存在一个DerivedA
的基类BaseClass
,它可以在R
上访问,并且在BaseClass
类中命名的x
(即BaseClass::x
)可以在R
上访问,因此根据第四个重点,DerivedA::x
可以在R
上访问。