我有一些(现实世界)代码,其结构基本上如此:
class C
{
public:
C(int x = 0) : m_x(x) {}
friend int foo(const C& c, int y) { return c.m_x + y; }
private:
int m_x;
};
class Z
{
public:
int foo(int y) {
// The problematic call:
return foo(c, y);
}
private:
C c;
};
我理解,foo
内Z::foo
的调用需要消除歧义。我不明白的是,适当的范围是什么?我期望C
- 朋友foo
的声明在全局命名空间中,但调用::foo
不起作用,GCC和Clang都将此报告为错误。
但是,如果我将C
+朋友的声明更改为:
class C
{
public:
C(int x) : m_x(x) {}
friend int foo(const C& c, int y);
private:
int m_x;
};
int foo(const C& c, int y) { return c.m_x + y; }
一切正常,我可以(在Z::foo
中)引用::foo
。
所以这是我的问题:在第一个例子中,C
- 朋友foo
的范围是什么,如果它不在全局命名空间中?是否无法从foo
内引用全球Z::foo
?而且,我的第一个和第二个例子之间有什么区别?