未命名的命名空间

scd*_*dmb 5 c++ namespaces g++

有以下代码:

#include <iostream>

using namespace std;

namespace
{
    int funkcja()
    {
        cout << "unnamed" << endl;
        return 0;
    }
}

int funkcja()
{
    cout << "global" << endl;
    return 0;
}

int main()
{
    ::funkcja(); //this works, it will call funkcja() from global scope
    funkcja(); //this generates an error 
    return 0;    
}
Run Code Online (Sandbox Code Playgroud)

我用g ++.在这种情况下,有没有办法从未命名的命名空间调用函数?可以使用:: function从全局范围调用函数,但是如何从未命名的命名空间调用函数?编译器生成错误:

prog3.cpp: In function ‘int main()’:
prog3.cpp:43:17: error: call of overloaded ‘funkcja()’ is ambiguous
prog3.cpp:32:5: note: candidates are: int funkcja()
prog3.cpp:25:6: note:                 int<unnamed>::funkcja()
Run Code Online (Sandbox Code Playgroud)

CB *_*ley 5

匿名命名空间的工作方式是,在其中声明的名称在封闭范围中自动可见,就像using namespace name_of_anonymous_namespace;已发出 a 一样。

因此,在您的示例中,名称funkcja是不明确且不可消除歧义的[新词!]。看来您并不真正需要匿名名称空间,您确实需要一个正确命名的名称空间。


Alo*_*ave 4

在这种情况下有没有办法从未命名的名称空间调用函数?
不,不适合你。

匿名/未命名命名空间 允许变量和函数在整个翻译单元内可见,但在外部不可见。尽管未命名命名空间中的实体可能具有外部链接,但它们实际上由其翻译单元唯一的名称限定,因此永远无法从任何其他翻译单元中看到。

这意味着未命名命名空间内的函数funkcja在定义全局函数的翻译单元中可见funkcja。这会导致在全局范围内定义两个相同的命名函数,从而导致重新定义错误。

如果funkcja仅存在于您的未命名命名空间中,那么您将能够::funkcja像在全局范围内一样调用它。总之,您可以根据 UnNamed 命名空间所在的范围调用 UnNamed 命名空间中的函数。