gpt4 book ai didi

c++ - 命名空间内类的友元函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:25:11 24 4
gpt4 key购买 nike

关于这段代码,我有两个问题:

namespace A { class window; }

void f(A::window);

namespace A
{
class window
{
private:
int a;
friend void ::f(window);
};
}

void f(A::window rhs)
{
std::cout << rhs.a << std::endl;
}

1) 为什么我需要通过执行::f(window) 将窗口类中的成员函数 f 限定为全局的?

2) 为什么在这种特殊情况下我需要预先声明函数 f(A::window) ,而当类未在命名空间内定义时,可以在函数声明为 friend 之后声明函数.

最佳答案

当您将 f() 声明为友元时,如果还没有前向声明,它实际上是在包含类(在本例中为 A)的封闭命名空间中完成的目前。

所以这个...

namespace A
{
class window
{
private:
friend void ::f(window);
};
}

基本上变成了这个...

namespace A
{
class window;
void f(window);

class window
{
private:
friend void f(window);
};
}

编辑:这里是 C++ 标准的一个片段,它明确地讨论了这种情况:

Standard 7.3.1.2 / 3 :

Every name first declared in a namespace is a member of that namespace. If a friend declaration in a nonlocal 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 (3.4.1) or by qualified lookup (3.4.3) until a matching declaration is provided in that namespace scope (either before or after the class definition granting friendship).

关于c++ - 命名空间内类的友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10937096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com