c++ - "friend struct A;"和 "friend A;"语法有什么区别?

标签 c++ c++11 friend

做和做有什么区别:

struct A;
struct B { friend struct A; };

struct A;
struct B { friend A; };

第二部分省略struct是什么意思?

最佳答案

不同的是,如果你写friend A;A必须是一个已知的类型名,也就是说它必须在之前声明。

如果你写friend struct A;,这本身就是A的声明,所以不需要事先声明:

struct B { friend struct A; }; // OK

虽然有一些微妙之处。例如,friend class/struct A 在类 B 的最内层封闭命名空间中声明类 A(感谢 Captain Obvlious):

class A;
namespace N {
    class B {
        friend A;         // ::A is a friend
        friend class A;   // Declares class N::A despite prior declaration of ::A,
                          // so ::A is not a friend if previous line is commented
    };
}

还有其他几种情况,你只能写friend A:

  1. A 是一个类型定义名称:

    class A;
    typedef A A_Alias;
    
    struct B {
        // friend class A_Alias;  - ill-formed
        friend A_Alias;
    };
    
  2. A 是模板参数:

    template<typename A>
    struct B { 
        // friend class A;  - ill-formed
        friend A;
    };
    

关于c++ - "friend struct A;"和 "friend A;"语法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26538374/

相关文章:

C++ 从 friend 类访问成员函数

c++ - 任务管理器的精确度如何?

android - 为原生 WebRTC 添加 H.264 支持

c++ - OSX 与 Linux : how to deal with unsigned long and uint64_t?

c++ - 模板类型的 ADL 和友元函数

c++ - 在 friend 的类中包含头文件

C++控制台屏幕大小

c++ - std::shared_ptr 在一位作家多读者设计中是线程安全的吗?

C++ 类变量 std::function 具有默认功能并且可以更改

C++ 参数包,受限于单一类型的实例?