命名空间中的类的朋友功能

编程入门 行业动态 更新时间:2024-10-28 04:28:36
本文介绍了命名空间中的类的朋友功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I've two question about this code bellow:

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限定为全局变量?

1) why do I need to qualify the member function f inside window class to be global by doing ::f(window) ?

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

2) why do I need to predeclare the function f(A::window) in this particular case, whereas when the class is not defined inside a namespace it's ok for the function to be declared after the function is declared a friend.

推荐答案

如果将f()声明为好友,则实际上是在包含类的封闭名称空间(在本例中为A)中完成的,如果前向声明为还不存在.

When you declare f() as a friend it's actually done in the enclosing namespace of the containing class (A in this case) if a forward declaration is not already present.

所以这个...

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

基本上就是这个...

essentially becomes this...

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

以下是C ++标准的摘要,明确讨论了这种情况:

Here is a snippet from the C++ standard that explicltly talks about this scenario:

标准7.3.1.2/3:

Standard 7.3.1.2 / 3 :

首先在名称空间中声明的每个名称都是该名称空间的成员. 如果非本地类中的朋友声明首先声明了一个类或函数,则该朋友类或函数是最内层的封闭命名空间的成员.通过不合格的查找找不到朋友的名称(3.4.1) )或通过合格查找(3.4.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).

更多推荐

命名空间中的类的朋友功能

本文发布于:2023-11-09 14:58:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572668.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:功能   朋友   空间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!