朋友困惑
$11.4/5 - “[...]类中定义的友元函数位于定义它的类的(词法)范围内[...]”
这句话是什么意思?
struct A{
typedef int MYINT;
void f2(){f();} // Error, 'f' is undefined
friend void f(){MYINT mi = 0;} // Why does this work, shouldn' it be A::MYINT?
void f1(){f();} // Error, 'f' is undefined
};
int main(){}
这里令人困惑的是,从“A::f1”调用“f”是可以理解的。然而,当朋友处于交友类的“词汇”范围内时,为什么从“A::f2”调用“f”格式不正确? “词法”范围是什么意思?
同样的类型,为什么在“f”中使用“MYINT”就可以了?难道不应该是 'A::MYINT' 吗?
如果我将“A *”类型的参数添加到“f”,则“f1”和“f2”都可以通过 ADL 找到“f”。这是可以理解的。
$11.4/5 - "[...]A friend function defined in a class is in the (lexical) scope of the class in which it is defined[...]"
What does this statement mean?
struct A{
typedef int MYINT;
void f2(){f();} // Error, 'f' is undefined
friend void f(){MYINT mi = 0;} // Why does this work, shouldn' it be A::MYINT?
void f1(){f();} // Error, 'f' is undefined
};
int main(){}
What is confusing here is that the call to 'f' from 'A::f1' is quiet understandable. However why is call to 'f' from 'A::f2' ill-formed, when a friend is in 'lexical' scope of the befriending class? What does 'lexical' scope mean?
At the same type why is the usage of 'MYINT' in 'f' OK? Shouldn't it be 'A::MYINT'?
If I add a parameter of type 'A *' to 'f', then both 'f1' and 'f2' are able to find 'f' because of ADL. This is understandable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您仅引用了 §11.4/5 的部分内容。根据它,
f()
应该首先在类外声明(函数应该具有命名空间范围)。试试这个:至于第二个问题,没关系,因为你引用了§11.4/5的部分内容。
f()
遵循与该类的静态成员函数相同的名称绑定规则,并且对封闭类的成员没有特殊的访问权限。You have quoted only part of §11.4/5. According to it
f()
should be declared out of class first (function should have namespace scope). Try this:As for second question, it is ok because of quoted by you part of §11.4/5.
f()
obeys the same rules for name binding as a static member function of that class and has no special access rights to members of an enclosing class.这是我对查询的一部分的解释:
中,要查找的名称是“MYINT”,这是一个非限定名称。在类中内联定义的友元“f”的定义中查找此名称将在与“A”的成员函数相同。
Here is my interpreation of one part of my query which is
In our case, the name to be looked up is 'MYINT' which is a unqualified name. The lookup for this name inside the definition of the friend 'f' which is defined inline in the class would would be done in the same was as it would be for member functions of 'A'.