c – Friend函数在类中是不可见的

前端之家收集整理的这篇文章主要介绍了c – Friend函数在类中是不可见的前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码
struct M {
    friend void f() {}
    M() {
        f(); // error: 'f' was not declared in this scope
    }
};

int main() {
    M m;
}

Live example

g 4.8和clang3.4都无法编译,因为f在M中是不可见的,所以他们说.

然而,该标准给出了类似代码的示例

class M {
  friend void f() { } // definition of global f,a friend of M,// not the definition of a member function
};

并说

A friend function defined in a class is in the (lexical) scope of the
class in which it is defined.

(ISO / IEC 14882:2011 11.3朋友[class.friend] p6,p7)

从这里我无法理解编译器如何找不到f,它被定义在同一个类中.

两个编译器都有同样的错误.
那么,我错过了什么?

解决方法

朋友声明指出,在周围的命名空间中,一个名为f的函数是该类的朋友;但是它不会将名字f引入命名空间.它不可用(除了通过参数相关的查找),直到它在命名空间中声明.

相关规则为C 11 7.3.1.2/3:

If a friend declaration in a non-local class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by unqualified lookup or by qualified lookup until a matching declaration is provided in that namespace scope.

原文链接:https://www.f2er.com/c/114642.html

猜你在找的C&C++相关文章