c++ - "friend"一个类是否扩展到该类中声明的类?

标签 c++ friend

我有以下代码,其中 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/

相关文章:

c++ - 相机校准结果 : why it is similar to input?

android - Facebook API 是否允许发送和接受好友请求?

c++ - 当涉及多个模板类型时,是否可以缩小类和函数之间的友元关系?

c++ - 如何在 c++ 中为 oracle db 编写 udf

c# - 从 C# 到非托管 C++ 库中执行 DllImport 时出现 MSBuild 4.0 依赖性问题

c++ - 默认的 move 构造是什么?

c++ - 类的友元函数产生错误 : "no ' __ _' member function declared"

c++ - 如何使用友元函数在模板类之外重载运算符==?

c++ - C++ 类模板中的友元比较和关系运算符

c++ - 在 Linux 和 Mac OS X 上检测已安装的驱动器