一个类定义的朋友函数属于哪个范围? [英] Which scope does an in-class-defined friend function belong to?

查看:201
本文介绍了一个类定义的朋友函数属于哪个范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A {
    friend void f() {}
};

// void f() {}  // compile error: redifinition of 'void f()'

int main() {
    f();  // compile error: 'f' is not declared in this scope
}

可以看到在上面的例子中,如果 f A 中调用, t找到 f ,这让我想到 f 不在这个范围。但是,当添加了具有相同签名的函数的超出规定的定义时,编译器会发出函数重定义的错误,这给了我相反的想法: f

As you can see in the above example, if f is called in A's enclosing namespace scope, the compiler just can't find f, which gives me the idea that f is not in this scope. But when an out-of-calss definition of a function with the same signature is added, the compiler issues an error of function redefinition, which gives me the opposite idea that f is actually in this scope.

所以,我困惑了一个类定义的友元函数属于哪个范围。

So, I'm puzzled which scope an in-class-defined friend function belongs to.

推荐答案

它在包含类的命名空间中。

It's in the namespace containing the class.

但是,如果它只在类中声明,可通过参数相关查找获得。所以这将工作,参数类型 A 在周围的命名空间中找到 f

However, if it's only declared in the class, then it's only available by argument-dependent lookup. So this would work, with the argument type A finding f in the surrounding namespace:

class A {
    friend void f(A) {}
};

int main() {
    f(A());    // OK: uses ADL
    ::f(A());  // Error: doesn't use ADL, and can't find the name without it
}

这通常用于重载的运算符,它只能由ADL找到。

This is often used for overloaded operators, which can only be found by ADL anyway.

如果你声明,而不是重新定义函数命名空间范围。

Your version would work if you declared, rather than redefined, the function at namespace scope.

void f();

这篇关于一个类定义的朋友函数属于哪个范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆