嵌套类访问封闭的类成员 [英] Nested class access to enclosing class members

查看:72
本文介绍了嵌套类访问封闭的类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘自Stanley Lippman等人的C ++ Primer 5版(19.5):

From C++ Primer 5th edition By Stanley Lippman et al(19.5):

嵌套类可以具有与非嵌套类相同的成员.就像任何其他类一样,嵌套类使用访问说明符控制对其自身成员的访问.封闭类对嵌套类的成员没有特殊的访问权限,嵌套类对封闭类的成员没有特殊的访问权限.

加粗部分是否有真相?我发现没有提到嵌套类被限制访问标准(9.7 N3337)中的封闭类成员,并且以下代码可以很好地进行编译(g ++ 5.2.0)

Is there any truth to the bolded part? I could find no mention of the nested class being restricted access to enclosing class members in the standard (9.7 N3337) and the following code compiles fine (g++ 5.2.0)

#include <iostream>

struct A{
private:
    typedef int woah;
public:
    struct B{
        woah x = 5;
        void test() { A f; std::cout << f.x;}
    };
private:
    int x = 5;
};

int main(){
    A::B j;
    j.test();
}

这里有两个部分:

  1. B 访问私有类型别名 woah 定义其自己的成员.
  2. B 的成员函数 test 访问 A 对象的私有 x 成员.
  1. B accesses the private type alias woah to define its own member.
  2. The member function test of B accesses the private x member of an A object.

当然,事实似乎恰恰相反,正如引号所说: A 无法访问 B 的私有成员(此示例未显示).那么这是我这本书的失误还是我误解了它在说什么?

Of course the opposite seems to be true as the quote says: A cannot access private members of B (not that this example shows that). So is this a blunder on my book's part or am I misunderstanding what it is saying?

推荐答案

该标准认为,缺少对嵌套类的访问权限是标准中的一个错误,并已得到纠正.现在,嵌套类具有与所有成员相同的访问级别,即总访问权限.

It was decided that the lack of access of nested classes was a mistake in the Standard, and subsequently rectified. Now nested classes enjoy the same levels of access as all members, namely total access.

这篇关于嵌套类访问封闭的类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆