【发布时间】:2019-10-22 11:57:02
【问题描述】:
考虑以下代码:
namespace Foo1 {
void add( int ) {}
void subtract( int ) {}
}
namespace Foo2 {
class Bar {
public:
friend void add( Bar ) {}
};
void subtract( Bar ) {}
void xxx() {
int i = 0;
using namespace Foo1;
add( i ); // Is this an error or not?
subtract( i ); // This is an error due to name hiding
}
}
在Foo2::xxx() 中,我使用 using 命名空间来访问Foo1::add 和Foo1::subtract。调用减法显然是一个错误,因为 Foo2::subtract
隐藏名称。但是Foo2::add 不应该在Foo2 中真正可见,因为它只能
可以使用 ADL 找到,它不应隐藏 Foo1::add。我的理解正确吗?
我已经在多个版本的 MSVC 和 gcc 上尝试过上述代码。前者一贯
拒绝了add(i) 电话,但我不清楚错误消息。后者一直接受它。以下哪个(如果有)是正确的?
【问题讨论】:
-
@Peter - 朋友不是班级的成员,而是他们的朋友
-
@Peter 友元函数实际上并不属于该类,即使它们是在类体内定义的。
-
@Peter 一个朋友不是该班级的成员。绝对没有
Foo2::Bar::add。其中定义的add是Foo2的成员,但不会自动声明为可见的Foo2声明,因此只能通过参数相关查找找到。
标签: c++