如何在C ++中正确使用命名空间? [英] How do you properly use namespaces in 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屋!