如何在 C++ 中正确使用命名空间? [英] How do you properly use namespaces in C++?

查看:23
本文介绍了如何在 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++ 中正确使用命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆