【发布时间】:2011-10-22 15:24:38
【问题描述】:
下面是访问实例的受保护字段 x 的一个微妙示例。 B 是 A 的子类,因此 B 类型的任何变量也是 A 类型。 为什么 B::foo() 可以访问 b 的 x 字段,但不能访问 a 的 x 字段?
class A {
protected:
int x;
};
class B : public A {
protected:
A *a;
B *b;
public:
void foo() {
int u = x; // OK : accessing inherited protected field x
int v = b->x; // OK : accessing b's protected field x
int w = a->x; // ERROR : accessing a's protected field x
}
};
这是我在使用 g++ 时遇到的错误
$ g++ -c A.cpp
A.cpp: In member function ‘void B::foo()’:
A.cpp:3: error: ‘int A::x’ is protected
A.cpp:14: error: within this context
【问题讨论】:
标签: c++ inheritance protected