问题描述
我认为这里的大多数C ++程序员都会同意污染全局名称空间是一个坏主意,但是有时候可以忽略此规则吗?
I think most C++ programmers here would agree that polluting the global namespace is a bad idea, but are there times when this rule can be ignored?
例如,我有一个需要在特定应用程序中使用的类型-我应该这样定义它:
For example, I have a type that I need to use all over a particular application - should I define it thus:
mytypes.h
typedef int MY_TYPE;
foo.cpp
MY_TYPE myType;
或使用名称空间:
mytypes.h
namespace ns {
typedef int MY_TYPE;
}
foo.cpp
ns::MY_TYPE myType;
...
using namespace ns;
MY_TYPE myType;
您更喜欢哪个?在某些时候可以接受第一种方法吗?
Which do you prefer? Are there times when it is acceptable to use the first method?
推荐答案
我使用命名空间将应用程序特定代码中的库代码分区,并在一个大型项目中对组成该项目的各个模块进行分区.
I use namespaces for partitioning library code from application-specific code, and in a big project to partition the various modules that make up the project.
因此,全局名称空间对于跨应用程序中多个模块使用的特定于应用程序的类型和功能很有用.
The global namespace is thus useful for application-specific types and functions that are used across multiple modules in the application.
因此,如果在整个应用程序中都使用了MY_TYPE
,请将其放在全局名称空间中,否则将其放在命名名称空间中.
So, if your MY_TYPE
is used throughout your application, put it in the global namespace, otherwise put it in a named namespace.
这篇关于污染全局名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!