加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:29:06 所属栏目:百科 来源:网络整理
导读:我有以下代码: 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 { fr
我有以下代码:
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读