c++ - C++中嵌套结构的 friend

标签 c++ struct nested

我知道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/

相关文章:

javascript - 如何在 for...in 中获取嵌套对象属性的正确属性?

go - 避免与在 go 中返回 2 个值的函数一起嵌套?

C++值初始化

c# - 通过自定义结构类型验证原始 .NET 值类型 : Is it worth the effort?

c - 为什么一个结构不能有一个与它自己类型相同的成员?

C:将嵌套结构数组传递给函数

c - 使用C中的循环制作x的楼梯,但我不断得到正方形

C++ - 在 HDF5 中设置列​​名

c++ - 如何用条件运算符表示三种情况?

c++ - strncpy 相当于 std::copy