究竟什么是命名空间以及为什么它是必要的
我现在正在学习 C++,在每个项目开始时,我的导师都会写一句话:
I am learning C++ right now, and at the beginning of every project my instructor puts a line that says:
using namespace std;
我了解它使您不必调用包含头文件名称(如 iostream::stdout)的头文件中的函数,而只需调用标准输出.
I understand that it keeps you from having to call functions in headers you include with their header name like iostream::stdout and instead just call stdout.
但是这行代码到底告诉 C++ 做什么.什么是命名空间,什么是 std?
除了 python 之外,我也是编程新手,所以切换到新的范例对我来说非常困惑.
推荐答案
来自 cppreference.com:
From cppreference.com:
命名空间提供了一种防止大型名称冲突的方法项目.
Namespaces provide a method for preventing name conflicts in large projects.
在命名空间块内声明的符号被放置在命名范围内这可以防止它们被误认为是同名符号在其他范围内.
Symbols declared inside a namespace block are placed in a named scope that prevents them from being mistaken for identically-named symbols in other scopes.
允许有多个同名的命名空间块.全部这些块中的声明在命名范围内声明.
Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope.
命名空间可以避免名称冲突,例如标准库定义了 sort()
但这是一个非常好的排序函数名称,感谢命名空间,您可以定义自己的 sort()
因为它不会与标准命名空间在同一个命名空间中.
A namespace works to avoid names conflicts, for example the standard library defines sort()
but that is a really good name for a sorting function, thanks to namespaces you can define your own sort()
because it won't be in the same namespace as the standard one.
using 指令告诉编译器在当前范围内使用该命名空间,以便您可以这样做
The using directive tells the compiler to use that namespace in the current scope so you can do
int f(){
std::cout << "out!" << std::endl;
}
或:
int f(){
using namespace std;
cout << "out!" << endl;
}
当您使用来自另一个命名空间的大量内容时,它会很方便.
it's handy when you're using a lot of things from another namespace.
来源:命名空间 - cppreference.com
相关文章