问题描述
摘自Stanley Lippman等人的C ++ Primer 5版(19.5):
From C++ Primer 5th edition By Stanley Lippman et al(19.5):
加粗部分是否有真相?我发现没有提到嵌套类被限制访问标准(9.7 N3337)中的封闭类成员,并且以下代码可以很好地进行编译(g ++ 5.2.0)
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();
}
这里有两个部分:
-
B
访问私有类型别名woah
定义其自己的成员. - B 的成员函数
test
访问A
对象的私有x
成员.
B
accesses the private type aliaswoah
to define its own member.- The member function
test
ofB
accesses the privatex
member of anA
object.
当然,事实似乎恰恰相反,正如引号所说: A
无法访问 B
的私有成员(此示例未显示).那么这是我这本书的失误还是我误解了它在说什么?
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?
推荐答案
该标准认为,缺少对嵌套类的访问权限是标准中的一个错误,并已得到纠正.现在,嵌套类具有与所有成员相同的访问级别,即总访问权限.
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.
这篇关于嵌套类访问封闭的类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!