【问题标题】:Use of namespace in C++? [duplicate]在 C++ 中使用命名空间? [复制]
【发布时间】:2013-08-01 18:02:21
【问题描述】:
#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++ 中命名空间的这种使用感到好奇。我开始阅读有关命名空间的文档,我看到很多示例调用命名空间的名称,例如“命名空间优先”,但在命名空间声明之后没有任何例子。

【问题讨论】:

  • 这里有问题吗?
  • 这是一个未命名的命名空间stackoverflow.com/questions/154469/…
  • 我认为这是一个匿名命名空间。我记得有人告诉我上面是 C++ 实现全局变量非外部链接的方式(而在 C 中你声明它们static)。

标签: c++ namespaces


【解决方案1】:

这是一个匿名或未命名的命名空间。命名空间中的项目(在此示例中仅为 gd3dApp)在翻译单元中可见,但无法在外部引用,因为没有名称来限定它们。

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

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

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

【讨论】:

    猜你喜欢
    • 2011-05-03
    • 2012-01-18
    • 1970-01-01
    • 2011-01-20
    • 2013-06-14
    • 2011-05-05
    • 2017-09-13
    • 2011-01-02
    相关资源
    最近更新 更多