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

问题描述

有此代码:

#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.

  • 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):

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

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.

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

08-21 08:17