简体   繁体   English

命名空间的类的朋友,未在命名空间中声明和定义

[英]Namespace's class's friend that is not declared and defined in the namespace

Is it right to do so:这样做是否正确:

void f();

namespace ns
{
    class C
    {
        int m;
        friend void ::f();
    };
}

void f()
{
    ns::C c;
    c.m = 2;
}

? ?

The code is compiled successfully in VS.代码在VS中编译成功。 But I can't find anything about qualifying a namespace for a friend declaration in the standard.但是我找不到任何关于在标准中为朋友声明限定名称空间的信息。 Is it even legal?它甚至合法吗? Can someone provide the link or the quote from the standard?有人可以提供标准的链接或报价吗?

Yes it's legal.是的,这是合法的。

A namespace is little more than a way of adding another layer of descrimination for functions, classes, &c.. namespace只不过是为函数、类等添加另一层描述的一种方式。

Any function can be marked as a friend inside a class , even if that class is in a different namespace to the function.任何 function 都可以在class中标记为friend ,即使 class 与class位于不同的namespace中。 The function could be in a namespace too. function 也可以在namespace中。

There's no specific section in the standard on this, but it's a corollary of the standard.标准中没有关于此的特定部分,但它是标准的必然结果。 This reference is a starting point: https://en.cppreference.com/w/cpp/language/namespace此参考是一个起点: https://en.cppreference.com/w/cpp/language/namespace

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM