在类中定义friend
我可以把friend函数/类的定义放在另一个类中吗?我的意思是这样:
Can i put definition of friend function / class inside another class? I mean something like this:
class Foo
{
friend void foo() {} // 1
friend class Bar {}; // 2
};
gcc编译好友函数,但无法编译好友类。
gcc compiles friend function, but can't compile friend class.
您可以在朋友声明中定义朋友
具有无法以任何其他方式获得的有趣的行为(在封装类型是模板的情况下)。
You can define a friend
function in the friend declaration, and it has interesting behavior that cannot be obtained any other way (in the case of the enclosing type being a template).
您不能在朋友声明中定义朋友
类,需要。如果您要创建具有完全访问权限的新类型 inline ,则只需创建嵌套类型即可。作为一个成员,它将完全访问封闭类型。唯一的区别是,类型不会在命名空间级别找到,但是如果需要可以添加typedef(或者,在命名空间级别定义类,并只声明类中的友谊)。
You cannot define a friend
class in the friend declaration, and there is no need for that. If you want to create a new type inline with full access, you can just create a nested type. Being a member it will have full access to the enclosing type. The only difference is that the type will not be found at namespace level, but you can add a typedef if needed (or alternatively, define the class at namespace level and just declare the friendship inside the class).
class Outer {
int x;
class Inner {
static void f( Outer& o ) { o.x = 5; } // fine
};
};