简体   繁体   English

根据ISO 2003,内部类访问外部私有成员

[英]Inner class access to private members of outer, according to ISO 2003

As described in ISO C++ 2003 如ISO C ++ 2003中所述

§11.8 Nested classes [class.access.nest] §11.8嵌套类[class.access.nest]

The members of a nested class have no special access to members of an enclosing class, nor to classes or functions that have granted friendship to an enclosing class; 嵌套类的成员对封闭类的成员没有特殊访问权限,也没有对已经为封闭类授予友谊的类或函数的特殊访问权限。 the usual access rules (clause 11) shall be obeyed. 应遵守通常的准入规则(第11条)。 The members of an enclosing class have no special access to members of a nested class; 封闭类的成员对嵌套类的成员没有特殊访问权限; the usual access rules (clause 11) shall be obeyed. 应遵守通常的准入规则(第11条)。

[Example: [例:

 class E { int x; class B { }; class I { B b; // error: E::B is private ERROR 1 int y; void f(E* p, int i) { p->x = i; // error: E::x is private ERROR 2 } }; int g(I* p) { //return p->y; // error: I::y is private ERROR 3 } }; int main() {} 

—end example] - 末端的例子]

So I think that clang and g++ are wrong as they compile this code successfully. 所以我认为clangg ++是错误的,因为他们成功编译了这段代码。

Or do I understand something wrong? 或者我理解错了什么?

Standard says about "have no special access", but not about "have no access at all". 标准说“没有特殊访问权限”,但不是“完全没有权限”。 Nested class is a same member of outer class as any other member. 嵌套类与外部类的成员与任何其他成员相同。

It is not clearly said in C++03 standard, but C++11 contains it explicitly: 在C ++ 03标准中没有明确说明,但C ++ 11明确地包含它:

11.7 Nested classes [class.access.nest] 11.7嵌套类[class.access.nest]

1 A nested class is a member and as such has the same access rights as any other member. 1嵌套类是成员,因此具有与任何其他成员相同的访问权限。

This behaviour has changed since 2003. The relevant clause in Working Draft N4926 (C++17) now reads: 自2003年以来,这种行为发生了变化。工作草案N4926(C ++ 17)中的相关条款现在为:

§11.7 Nested classes [class.access.nest] §11.7嵌套类[class.access.nest]

A nested class is a member and as such has the same access rights as any other member. 嵌套类是成员,因此具有与任何其他成员相同的访问权限。 The members of an enclosing class have no special access to members of a nested class; 封闭类的成员对嵌套类的成员没有特殊访问权限; the usual access rules (Clause 11) shall be obeyed. 应遵守通常的访问规则(第11条)。

So the access is one way: nested class members can access enclosing class members, but not vice versa. 因此访问是一种方式:嵌套类成员可以访问封闭的类成员,但反之亦然。

For instance: 例如:

class Enclosing
{
  int n;
  class Nested
  {
    int n;
    int f (Enclosing& E)
    {
      return E.n; // OK
    }
  } ;
  int f (Nested& N)
  {
    return N.n; // Error: Nested::n is private
  }
} ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM