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

问题描述

此代码在msvc / g ++上编译:

This code compiles on msvc/g++:

class A{
protected:
    int i;
    class B{
    public:
        A* a;
        B(A* a_)
        :a(a_){
        }
        void doSomething(){
            if (a)
                a->i = 0;//<---- this part
        }
    };
public:
    A()
    :i(0){
    }
};

正如你所看到的,B可以访问封闭类的protected部分, t声明为朋友。

As you can see, B gets access to "protected" section of enclosing class, although it isn't declared as friend.

这是一个标准(符合标准)行为吗?

Is this a standard(standard-conforming) behavior?

我有时使用这个功能,但我不记得一个规则,说嵌套的受保护类应该自动获得对封闭类的所有受保护数据的访问。

I use this feature sometimes, but I don't remember a rule saying that nested protected class should automatically get access to all protected data of enclosing class.

推荐答案

在C ++ 03标准中,11.8p1说:

In the C++03 standard, 11.8p1 says:

但是,的分辨率(标准)说明了相反的情况,因此定义了你看到的行为:

However, the resolution for defect report 45 (to the standard) states the opposite, and hence defines the behavior you see:

在C ++ 0x中,11.8的文本已更改以反映此事实,因此这对于C ++ 03和C ++ 0x符合的编译器都是有效的行为。

In C++0x the text of 11.8 has been changed to reflect this fact, so this is valid behavior for both C++03 and C++0x conforming compilers.

另请参见中的com / cplusplus-programming / 110207-can-nested-class-access-parent-classs-private- .com 论坛。

See also this thread from the cprogramming.com forums.

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

07-12 06:43