问题
From C++ Primer 5th edition By Stanley Lippman et al(19.5):
A nested class can have the same kinds of members as a nonnested class. Just like any other class, a nested class controls access to its own members using access specifiers. The enclosing class has no special access to the members of a nested class, and the nested class has no special access to members of its enclosing class.
Is there any truth to the bolded part? I could find no mention of the nested class being restricted access to enclosing class members in the standard (9.7 N3337) and the following code compiles fine (g++ 5.2.0)
#include <iostream>
struct A{
private:
typedef int woah;
public:
struct B{
woah x = 5;
void test() { A f; std::cout << f.x;}
};
private:
int x = 5;
};
int main(){
A::B j;
j.test();
}
There being two parts here:
B
accesses the private type aliaswoah
to define its own member.- The member function
test
ofB
accesses the privatex
member of anA
object.
Of course the opposite seems to be true as the quote says: A
cannot access private members of B
(not that this example shows that). So is this a blunder on my book's part or am I misunderstanding what it is saying?
回答1:
It was decided that the lack of access of nested classes was a mistake in the Standard, and subsequently rectified. Now nested classes enjoy the same levels of access as all members, namely total access.
来源:https://stackoverflow.com/questions/34976995/nested-class-access-to-enclosing-class-members