我有以下代码:
class Base
{
private:
class NestedBase
{
public:
void Do() {}
};
public:
NestedBase nested;
};
int main()
{
Base b;
b.nested.Do(); // line A compiles
Base::NestedBase instance; // line B doesn't compile
}
NestedBase
类是 Base
的私有(private)嵌套类,因此 B 行不编译似乎很自然。但是,另一方面,变量 b
有公共(public)成员 nested
,我可以从 外部调用它的方法
(如 A 行)。在这种情况下,规范对私有(private)嵌套类(或其成员)的访问的确切规则是什么?标准对此有何规定?Do()
>Base
最佳答案
根据标准,$11.7/1 Nested classes [class.access.nest] :
A nested class is a member and as such has the same access rights as any other member.
所以,这很简单。 NestedBase
是 Base
类的 private
成员,所以 Base::NestedBase
不能在 中访问>主要()
。
b.nested.Do();
很好,因为 nested
和 Do()
都是 public
成员。 NestedBase
是 Base
的 private
嵌套类这一事实并不重要,与此无关。
关于C++:私有(private)嵌套类类型的公共(public)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34965014/