【发布时间】:2016-12-07 15:09:48
【问题描述】:
这是code:
class TestA
{
protected:
int test=12;
public:
TestA() {
cout << "test a: " << test << endl;
}
~TestA() {
}
};
class TestB : public TestA
{
public:
TestB(TestA *testA) {
cout << "test b: " << testA->test;
}
~TestB() {
}
};
int main ()
{
TestA *pTestA=new TestA();
TestB *pTestB=new TestB(pTestA);
}
我正在尝试使用指向TestA 类型对象的指针访问protected 成员(因此,TestA 的实例)。 TestB也派生自TestA
为什么我无法访问它?它是否只能在我需要的类“内”访问?不在使用指针/直接声明之外?
【问题讨论】:
-
我重新打开这个问题,因为这里提到的答案比旧的副本更好:accessing a protected member of a base class in another subclass。关闭另一个。
-
简短回答:因为标准规定这是禁止的。因此,符合标准的编译器将对其抛出错误。 YMMV,但我实际上将其称为标准中的错误。
-
@cmaster (请参阅我的答案中的示例代码)如果允许,则可以通过
B*类型的指针访问受保护的成员,该指针指向成员函数中D1的实例的D2。但D1和D2实际上是无关紧要的。这似乎违反直觉。
标签: c++ inheritance scope protected