我知道Thinking in C++ Bruce Eckel 的著作不是引用书,但我发现了一段奇怪的段落,我不明白它是否仍然适用于今天:
Making a structure nested doesn’t automatically give it access to private members. To accomplish this, you must follow a particular form: first, declare (without defining) the nested structure, then declare it as a friend, and finally define the structure. The structure definition must be separate from the friend declaration, otherwise it would be seen by the compiler as a non-member.
我实际上在没有将嵌套结构声明为友元的情况下尝试了这个并且它起作用了:
struct myStruct{
private:
int bar;
public:
struct nestedStruct{
void foo(myStruct *);
}a;
};
void myStruct::nestedStruct::foo(myStruct * p){
p->bar = 20;
}
为了修改基类的私有(private)成员,还需要声明嵌套结构体friend吗?
最佳答案
那句话是错误的。嵌套的内部类类型可以访问封闭类类型的所有成员(包括 private
)。
在 C++98 中情况并非如此,您的版本可能指的是标准的那个版本。在 C++03 和 C++11 中,引用不适用。
11.7 嵌套类[class.access.nest]
1 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.
关于c++ - C++中嵌套结构的 friend ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12868428/