访问内部类中外部类的私有成员数据 [英] Access to private member data of outer class in inner class

查看:190
本文介绍了访问内部类中外部类的私有成员数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有此代码:

#include <iostream>

class Outer{
    int a; // private data member of class Outer
public:
    Outer(): a(55){}
    class Inner{
    public:
        void fun(Outer ob){
            std::cout << ob.a << std::endl;
        }
    };
};

int main() {

    Outer::Inner object;
    object.fun(Outer()); // prints 55
    //std::cout << (Outer().a) << std::endl; error: 'int Outer::a' is private

    return 0;
} 

为什么内部类可以访问外部类的私有成员数据"a"?在本文之后适用于Linux的XL C/C ++ V8.0 ,不应进行编译,但是可以在g ++ 4.4.0上进行编译.

Why Inner class has access to private member data 'a' of class Outer? Following this article XL C/C++ V8.0 for Linux, it should not compile, however it compiles on g++ 4.4.0.

推荐答案

根据该文档,XL C/C ++ V8.0不支持C ++ 11,请参阅符合语言标准"一节.

According to that document XL C/C++ V8.0 does not support C++11, see the "Language standards compliance" section.

编译器支持以下针对C和C ++的编程语言规范:

The compiler supports the following programming language specifications for C and C++:

  • ISO/IEC 9899:1999(C99)
  • ISO/IEC 9899:1990(称为C89)
  • ISO/IEC 14882:2003(称为标准C ++)
  • ISO/IEC 14882:1998,该语言的第一个正式规范 (称为C ++ 98)
  • ISO/IEC 9899:1999 (C99)
  • ISO/IEC 9899:1990 (referred to as C89)
  • ISO/IEC 14882:2003 (referred to as Standard C++)
  • ISO/IEC 14882:1998, the first official specification of the language (referred to as C++98)

当前标准说(ISO/IEC 14882:2011 11.7):

The current standard says (ISO/IEC 14882:2011 11.7):

嵌套类是成员,因此具有与任何其他成员相同的访问权限.封闭类的成员对嵌套类的成员没有特殊的访问权限;应当遵守通常的访问规则(第11条).

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.

在以前的语言标准中,是否允许这种访问,或者至少不清楚是否应该允许这种访问,具体取决于您的解释.

In the previous language standard whether this access either wasn't allowed, or at the least it was unclear whether it should be allowed, depending on your interpretation.

这篇关于访问内部类中外部类的私有成员数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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