在C++中使用命名空间

Use of namespace in C++?

本文关键字:命名空间 C++      更新时间:2023-10-16
#include "d3dApp.h"
#include <WindowsX.h>
#include <sstream>
namespace
{
    // This is just used to forward Windows messages from a global window
    // procedure to our member function window procedure because we cannot
    // assign a member function to WNDCLASS::lpfnWndProc.
    D3DApp* gd3dApp = 0;
}
LRESULT CALLBACK
MainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    // Forward hwnd on because we can get messages (e.g., WM_CREATE)
    // before CreateWindow returns, and thus before mhMainWnd is valid.
    return gd3dApp->MsgProc(hwnd, msg, wParam, lParam);
}

我对C++命名空间的这种使用感到好奇。我开始阅读有关命名空间的文档,我看到很多示例调用命名空间的名称,例如"命名空间优先",但没有一个在命名空间声明之后没有任何内容。

这是一个

匿名或未命名的命名空间。 命名空间中的项(在此示例中只是gd3dApp(在翻译单元中可见,但不能在外部引用,因为没有名称来限定它们。

注意:这不会阻止外部链接。 看看这里: http://msdn.microsoft.com/en-us/library/yct4x9k5(v=vs.80(.aspx.

尽管未命名命名空间中的实体可能具有外部链接,但它们实际上由其翻译单元独有的名称限定,因此永远无法从任何其他翻译单元中看到。

这种技术略优于static,因为它也适用于typedef秒(不能声明为static(。