gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:38:04 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com