如何在c++中将多个文件包装到同一个命名空间中

how to wrap several files into the same namespace in C++

本文关键字:包装 文件包 命名空间 同一个 文件 c++      更新时间:2023-10-16

在c#中,很容易将所有类放入唯一的命名空间中。我了解在c++中名称空间是如何在一个简单的层次上工作的。但是,当涉及到将许多文件放在一起以显示为一个名称空间时,我真的很困惑。可能是这样的:

/* NetTools.cpp
blade 7/12/2014 */
using namespace std;
using namespace NetTools;
#include "NetTools.h"
int main()
{
   cout << "testing" << endl;
   return 0;
}
//####### EOF

/* NetTools.h 
blade 12/7/2014 */
#ifndef NETTOOLS_H
#define NETTOOLS_H
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
namespace NetTools
{
}
#endif
// #### EOF

/* Commands.h
blade 7/12/2014 */
#include "NetTools.h"
#ifndef COMMANDS_H
#define COMMANDS_H
namespace NetTools
{
}
#endif
// ###### EOF

我把每个类的声明在它的。h文件和实现在它的cpp文件中分开,但我希望所有的东西都在同一个命名空间。

您所展示的效果很好。

命名空间的一个基本属性是,如果不同的文件都在一个命名空间中声明相同的内容,编译器/链接器知道将它们放在一起,所以你得到一个包含所有文件中定义的所有内容的命名空间。

例如:

// file a
namespace A {
    class X;
}
// file b
namespace A {
    class Y;
}
// file c
namespace A {
    class Z;
}

…基本上相当于:

// one file
namespace A {
    class X;
    class Y;
    class Z;
}

匿名命名空间是例外。匿名命名空间在每个文件之间是分开的。例如:

// file a
namespace {
    void f();
}
// file b
namespace {
    int f();
}

这些不冲突,因为每个文件都有自己唯一的匿名命名空间

你所做的是正确的。这里的代码有一个问题:

/* NetTools.cpp
blade 7/12/2014 */
using namespace std;
using namespace NetTools; // put this AFTER #include "NetTools.h"
#include "NetTools.h"
int main()
{
   cout << "testing" << endl;
   return 0;
}

它适用于using namespace std; (不确定为什么),但它不适用于声明的命名空间。编译器需要在开始using它们之前看到它们:

/* NetTools.cpp
blade 7/12/2014 */
#include "NetTools.h"
using namespace std;
using namespace NetTools; // now this should work
int main()
{
   cout << "testing" << endl;
   return 0;
}

旁注:

你真的应该把所有放在include保护符里面:

/* Commands.h
blade 7/12/2014 */
#include "NetTools.h" // this should really go after the include guards
#ifndef COMMANDS_H
#define COMMANDS_H
namespace NetTools
{
}
#endif

不需要两次#include "NetTools.h" (即使包含保护)

/* Commands.h
blade 7/12/2014 */
#ifndef COMMANDS_H
#define COMMANDS_H
#include "NetTools.h" // like this
namespace NetTools
{
}
#endif