【问题标题】:how to wrap several files into the same namespace in C++如何在 C++ 中将多个文件包装到同一个命名空间中
【发布时间】:2014-07-12 10:39:40
【问题描述】:

在 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 文件中的实现分开,但我希望所有内容都在同一个命名空间中。

【问题讨论】:

  • 如果您将出现在不同头文件中的声明放入同一个命名空间,它们将共享它。我不明白你的实际问题是什么。还要注意,你应该在你的包含守卫中包含东西,而不是在外面。

标签: c++ c++11 namespaces preprocessor-directive


【解决方案1】:

你显示的效果很好。

命名空间的一个基本特性是,如果不同的文件都在同名命名空间中声明事物,编译器/链接器知道将事物放在一起,因此您会得到一个命名空间,其中包含所有文件中定义的所有内容。

例如:

// 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();
}

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

【讨论】:

  • 我认为这里的“文件”应该读作“翻译单元”,因为文件 a 和文件 b 中的未命名命名空间中的 f() 在文件 a 和文件 b 中声明了相同的函数文件 b #included 在同一个翻译单元中。
【解决方案2】:

你所做的是正确的。但是,您的代码存在问题:

/* 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;
}

旁注:

你真的应该把 everything 放在包含守卫中:

/* 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

【讨论】:

    猜你喜欢
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多