Dre*_*led 19 c++ inheritance gcc 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;
}
Run Code Online (Sandbox Code Playgroud)
用g ++(g++ classtest.cpp
)编译我收到以下错误:
classtest.cpp:在构造函数'DerivedB :: DerivedB()'中:
classtest.cpp:9:5:错误:'int BaseClass :: x'受保护
int BaseClass :: x;
^ classtest.cpp:25:32:错误:在此上下文中
std :: cout << DerivedA :: x;
当我用clang ++(clang++ classtest.cpp
)编译时,没有错误.
为什么g ++会返回编译错误?
我使用g ++版本5.1.0和clang ++版本3.6.1
T.C*_*.C. 17
GCC错误.[class.access.base]/P5:
成员
m
是在点访问R
时类命名N
,如果
m
作为N
公众的成员,或m
作为N
私人的成员,R
发生在班级的成员或朋友N
,或m
其中的一名成员N
被保护,并R
在成员或类的朋友发生N
,或者在类的成员P
来源于N
,其中m
作为成员P
是公共的,私人的,或保护,或- 存在一个基类
B
的N
也就是在访问R
,并m
在访问R
时,在课堂命名B
.
N
是DerivedA
,m
是x
,R
是...的构造者DerivedB
.存在一个基类BaseClass
的DerivedA
也就是在访问R
,并x
在课堂上命名BaseClass
(即BaseClass::x
)是明明白白访问R
,所以在第四个项目符号点,DerivedA::x
在访问的R
.