做和做有什么区别:
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
:
A
是一个类型定义名称:class A; typedef A A_Alias; struct B { // friend class A_Alias; - ill-formed friend A_Alias; };
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/