如何在c++中将多个文件包装到同一个命名空间中
how to wrap several files into the same namespace in C++
在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
相关文章:
- AcquireCredentialsHandleA() 返回 PFX 文件的0x8009030e(安全包中没有可用的凭据
- 禁止显示有关包含文件中 #pragma 包的警告
- 选择特定版本的 Visual Studio 命令行工具包,并根据特定版本的C++运行时环境编译文件
- 如何解开参数包包装器?
- 如何使用 AWS C++ 开发工具包在给定的开始和结束日期范围内列出 S3 中的文件
- 在实现文件中,我们应该更喜欢"using namespace"指令还是将实现包装在命名空间 { } 中?
- C 包装器C++库周围没有不必要的头文件
- 如何链接我自己的 .so 文件而不是操作系统捆绑包 .so 文件?
- 使用开发工具包将文件上传到 AWS C++
- Swig C++ python 包装器文件解释
- 将仅标头库的包含包装在单个 cpp 文件中
- 在C 中解开包装数据包
- 使用带有 MEX 包装器的帮助程序 C 文件从 MATLAB 2016 调用C++代码时出现问题
- TCP-Server以数据包结构(非Java客户端)发送文件
- 致命错误 C1083:无法打开包含文件:'atlbase.h' Pyinsane 包
- 可视化 将 TCP 服务器数据包保存到 C++ 中的文件
- Buildroot 包需要一个带有C++大文件错误的工具链
- 获取包含C++的捆绑包中文件的路径(CFBundleGetMainBundle)
- 短包装/拆包到内部
- 如何在visual studio 2010 C++中制作带有所需.dll和lib(opencv)文件的.exe文件包