问题
There is this code:
#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;
}
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.
回答1:
According to that document XL C/C++ V8.0 does not support C++11, see the "Language standards compliance" section.
The compiler supports the following programming language specifications for C and C++:
- 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)
The current standard says (ISO/IEC 14882:2011 11.7):
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.
回答2:
C++03 Standard $11.8/1: [class.access.nest]
The members of a nested class have no special access to members of an enclosing class, nor to classes or functions that have granted friendship to an enclosing class; the usual access rules (clause 11) shall be obeyed. 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.
But this is a defect:
45. Access to nested classes
In C++11, this has been corrected: in C++11 nested classes do have access to private members of the enclosing class (though the enclosing class still doesn't have access to private members of the nested classes).
C++11 Standard 11.7 Nested classes: says
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. [
class E {
int x;
class B { };
class I {
B b; // OK:E::I can accessE::B
int y;
void f(E* p, int i) {
p->x = i; // OK:E::I can accessE::x
}
};
int g(I* p) {
return p->y; // error:I::y is private
}
};
—end example]
The example is similar to the one you have in question and it clearly shows its valid behavior.
来源:https://stackoverflow.com/questions/8869907/access-to-private-member-data-of-outer-class-in-inner-class