考虑以下代码:
namespace base {
class Base {
protected:
class Nested {
protected:
Base* base;
public:
Nested(Base* _base) : base( _base ){}
virtual void test() {
base->foo();
/*
* hmm.. we can use protected methods
*/
base->bar();
}
};
protected:
Nested* nested;
void bar(){}
public:
void foo(){}
virtual void test() {
nested = new Nested(this);
nested->test();
}
};
};
namespace inherited {
class Base : public base::Base {
public:
Base()
: base::Base() {}
protected:
class Nested : public base::Base::Nested {
public:
Nested( inherited::Base* base )
: base::Base::Nested( base ) {}
public:
virtual void test() {
base->foo();
/*
* hmm.. and now they are not accessible
*/
// base->bar();
}
};
public:
virtual void test() {
foo();
bar();
nested = new Nested(this);
nested->test();
}
};
};
我的问题是为什么我们可以访问 from 的受保护方法/属性,但无法访问base::Base
from的相同方法/属性?base::Base::Nested
inherited::Base
inherited::Base::Nested
我唯一能想到的是这base::Base
是一种全局范围,base::Base::Nested
因此它们是可访问的。inherited::Base
是一种全局范围,inherited::Base::Nested
并且受保护的成员base::Base
不可访问。但是,公共继承不应该改变可见性范围,并且我不清楚无法访问的原因。