簡體   English   中英

如果在匿名命名空間中聲明函數,是否可以在全局命名空間中定義函數?

[英]Can a function be defined in global namespace if it is declared in an anonymous namespace?

在生產代碼中,我在.cpp文件中找到了它:

namespace
{
    void foo(); // declared in anonymous namespace, defined below
}

void bar() // declared in corresponding .h file, defined here
{
    ::foo(); // call foo
}

void ::foo() // intended to refer to the anonymous foo above
{
}

我們正在使用Visual Studio 2017.我偶然發現了這一點,因為intellisense給了我一個foo的警告,它找不到函數定義。 但是,它編譯和鏈接沒有錯誤,代碼執行它應該做的事情。

我詛咒它並發現gcc和clang拒絕這個代碼的原因與intellisense給我一個警告的原因相同。

所以我的問題是: 哪個編譯器是正確的,為什么?


此外,出於興趣,我在全局命名空間中添加了另一個foo聲明,如下所示:

namespace
{
    void foo();
}

void foo(); // another declaration

void bar()
{
    ::foo(); // which foo will be called?
}

void ::foo() // which foo will be defined?
{
}

現在,gcc給了我一個錯誤:

錯誤:聲明'void foo()'的顯式限定

Clang編譯它,但給了我一個警告:

警告:成員'foo'的額外資格[-Wextra-qualification]

並且msvc編譯它就好了。

再次,哪個編譯器 - 如果有的話 - 在這里是正確的?

查看未命名的命名空間上的cppreference頁面

此定義被視為具有唯一名稱的命名空間的定義,以及當前范圍中指定此未命名的命名空間的using-directive。

因此,“匿名”命名空間不是全局命名空間,也不是未命名的。 相反,它有一個編譯器提供的唯一名稱。 所以::foo() 不是匿名命名空間中的函數。 MSVC在這里不正確。

並且您無法在其匿名命名空間之外定義匿名命名空間函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM