How do you properly use namespaces in C++?(如何在 C++ 中正确使用命名空间?)
问题描述
我来自 Java 背景,使用包而不是名称空间.我习惯于将一起工作以形成完整对象的类放入包中,然后稍后从该包中重用它们.但现在我正在使用 C++.
I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.
如何在 C++ 中使用命名空间?您是为整个应用程序创建一个命名空间,还是为主要组件创建命名空间?如果是这样,您如何从其他命名空间中的类创建对象?
How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?
推荐答案
命名空间本质上是包.它们可以这样使用:
Namespaces are packages essentially. They can be used like this:
namespace MyNamespace
{
class MyClass
{
};
}
然后在代码中:
MyNamespace::MyClass* pClass = new MyNamespace::MyClass();
或者,如果您想始终使用特定的命名空间,您可以这样做:
Or, if you want to always use a specific namespace, you can do this:
using namespace MyNamespace;
MyClass* pClass = new MyClass();
遵循 bernhardrusch 说过,我根本不倾向于使用using namespace x"语法,我通常在实例化我的对象时明确指定命名空间(即我展示的第一个示例).
Following what bernhardrusch has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).
正如你在 下面问的那样,你可以使用任意数量的命名空间.
And as you asked below, you can use as many namespaces as you like.
这篇关于如何在 C++ 中正确使用命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中正确使用命名空间?
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01