gpt4 book ai didi

c++ - C++ 中的内部类会自动成为 friend 吗?

转载 作者:IT老高 更新时间:2023-10-28 12:12:24 25 4
gpt4 key购买 nike

如果我在 C++ 中定义了一个内部类,它会自动成为包含它的类的 friend 吗?例如,这是否合法:

class Outer {
public:
class Inner {
public:
void mutateOuter(Outer& o);
};

private:
int value;
};

void Outer::Inner::mutateOuter(Outer& o) {
o.value ++; // Legal? Or not?
}

我之所以问,是因为在我尝试过的某些编译器 (VS2003) 上,此代码不起作用,但我至少听说过它确实适用于某些编译器。我在 C++ 规范中找不到关于此的相关部分,如果有人能引用一些具体的内容来说明它是否合法,那就太好了。

最佳答案

在问过或多或少相同的问题后here我自己,我想分享 C++11 的(显然)更新的答案:

引自 https://stackoverflow.com/a/14759027/1984137 :

standard $11.7.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 shall be obeyed"

and the usual access rules specify that:

"A member of a class can also access all the names to which the class has access..."

specific examples has been given in the standard:

class E {
int x;
class B { };

class I {
B b; // OK: E::I can access E::B
int y;
void f(E* p, int i) {
p->x = i; // OK: E::I can access E::x
}
};
}

关于c++ - C++ 中的内部类会自动成为 friend 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5013717/

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