把函数定义写在类的友元声明处,这个函数的作用域在哪里?

无论如何也调用不了这个函数。

可以举个简单的例子。

#include <iostream>

class A{
    friend void f(){ std::cout<<"HelloWorld!"<<std::endl; }
};

int main()
{
    // 无法调用 f()

    return 0;
}

与其解释这个例子,我更想知道定义在友元声明处的函数,其所在作用域的具体规则!

阅读 1.8k
2 个回答

class.friend/7:

A function can be defined in a friend declaration of a class ...

Such a function is implicitly an inline function. A friend function defined in a class is in the (lexical) scope of the class in which it is defined. A friend function defined outside the class is not ([basic.lookup.unqual]).

如果我没记错的话,友元声明和函数真正的声明,定义是独立的。c++ primer友元部分讲的比较清楚,友元+模板类的规则也有,用的时候可以看下。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题