我有以下代码,其中 A 类将 B 类声明为 friend 。在 B 类中声明的 C 类是否应该能够查看 A 类的私有(private)声明/成员?
使用 CL 版本 16 (Visual Studio 2010) 编译时没有错误,但 gcc g++ 版本 4.1.1 给出错误“typedef int A::T is private in this context”。
函数调用作为 typedef 也会发生相同的行为(这就是我发现差异的方式)。
class A {
friend class B;
typedef int T;
};
class B {
A::T t; // ok
typedef A::T U; // ok
class C {
U u; // ok
A::T v; // compile error on gcc
};
};
我进行了短暂的搜索,但未能找到正确的搜索词。我还没有通读标准。之前有没有关于这个主题的问题,或者在 C++ FAQ 中提到过?标准暗示了哪种行为(如果有的话)?
最佳答案
来自标准文档,$11.4.2
Declaring a class to be a friend implies that the names of private and protected members from the class granting friendship can be accessed in the base-specifier s and member declarations of the befriended class.
标准文档中的一个例子。
class A {
class B { };
friend class X;
};
struct X : A::B { // OK: A::B accessible to friend
A::B mx; // OK: A::B accessible to member of friend
class Y {
A::B my; // OK: A::B accessible to nested member of friend
};
};
因此它应该可以正常工作。
关于c++ - "friend"一个类是否扩展到该类中声明的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5975421/