我目前正在使用21 天自学 C++,第二版这本书来学习 C++ 编码以及 Microsoft Visual C++ 2010 Express。在第 1 章的最后,有一个关于编写和编译以下代码的小练习:
#include <iostream>
int main ()
{
cout << "Hello World!\n";
return 0;
}
很简单,对吧?然而令我惊讶的是,由于这个错误,代码无法编译:
error C2065: 'cout' : undeclared identifier
我开始在网上搜索,很快找到了一些解决方案here .原来我不得不添加
using namespace std;
到我的代码!
但是书中没有提到命名空间,所以我认为这本书已经过时了。 (它使用 #include <iostream.h>
预处理器指令!)经过一些网络研究,我发现了很多关于命名空间的信息,namespace std
,以及 <iostream.h>
上的一些历史背景和 <iostream>
,所有这些新信息流都让我很困惑。 (更不用说所有关于医学 STD 的不必要的 Google 结果......)
到目前为止,我有一些问题:
- 如果我包含
iostream
图书馆,为什么是namespace
需要查找cout
?还有没有cout
可能会导致名称冲突的地方?如果有人可以为此提供图表,那就太好了。
另外,还有一些历史背景:
iostream.h
到底是什么?在更改为iostream
之前?做了
namespace
参与这一变革?
最佳答案
所有标准库定义都在命名空间 std 中。也就是说,它们不是在全局范围内定义的,因此要使用它们,您需要通过以下方式之一来限定它们:
std::cout
使用命名空间标准
使用 std::cout
举个例子:
// declarations
int global_variable;
namespace n {
int variable2;
}
global_variable
可以按原样访问:
int x;
x = global_variable;
但是variable2不是全局空间的一部分,而是namespace n
的一部分。
int x;
x = variable2; // error variable2 identifier not found.
所以你必须使用全名:
int x;
x = n::variable2;
你可以写一个快捷方式:
using namespace n;
int x;
x = variable2; // variable2 is searched in current namespace
// and in all namespaces brought in with using namespace
// Found ONLY in namespace n -> OK
或
using n::variable2; // this makes any unqualified reference to `variable2`
// to be resolved to `n::variable2`
int x;
x = variable2;
至于头文件,iostream.h
在没有标准之前被许多编译器使用。当委员会试图标准化时,他们决定使 C++ header 无扩展名,以免破坏与现有代码的兼容性。
关于c++ - iostream和命名空间std有什么关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23589657/