是C ++中的内部类自动的朋友吗? [英] Are inner classes in C++ automatically friends?

查看:155
本文介绍了是C ++中的内部类自动的朋友吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在C ++中定义一个内部类,它是否自动是包含它的类的一个朋友?例如,这是合法的:

If I define an inner class in C++, is it automatically a friend of the class that contains it? For example, is this legal:

class Outer {
public:
    class Inner {
    public:
        void mutateOuter(Outer& o);
    };

private:
    int value;
};

void Outer::Inner::mutateOuter(Outer& o) {
    o.value ++; // Legal?  Or not?
}

我问,因为在一些编译器我试过(VS2003)工作,但我听说至少有点轶事,它工作在一些编译器。我不能在C ++ spec中找到一个相关的部分,如果任何人可以引用一些具体的,说它是或不合法的将是巨大的。

I ask because on some compilers I've tried (VS2003) this code won't work, but I've heard at least anecdotally that it does work on some compilers. I can't find a relevant section in the C++ spec about this, and if anyone can cite something specific that would say that it is or is not legal that would be great.

推荐答案

在自己问了一个或多或少相同的问题后,我想要共享(显然)更新的C ++ 11答案:

After having asked more or less the same question here myself, I wanted to share the (apparently) updated answer for C++11:

引用 http://stackoverflow.com/a/14759027/1984137


标准$ 11.7.1

standard $11.7.1

嵌套类是一个成员,因此拥有与
任何其他成员相同的访问权限。一个封闭类的成员没有特殊的
访问成员的嵌套类;通常的访问规则应该是
遵守

"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 shall be obeyed"

,并且通常的访问规则指定:

and the usual access rules specify that:

类的成员还可以访问类
具有访问权限的所有名称...

"A member of a class can also access all the names to which the class has access..."

具体示例在标准中给出:

specific examples has been given in the standard:



class E {
    int x;
    class B { };

    class I {
        B b; // OK: E::I can access E::B
        int y;
        void f(E* p, int i) {
            p->x = i; // OK: E::I can access E::x
        }
    };
}

这篇关于是C ++中的内部类自动的朋友吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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