c++ - iostream和命名空间std有什么关系?

标签 c++ c++11 namespaces

我目前正在使用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 结果......)

到目前为止,我有一些问题:

  1. 如果我包含 iostream图书馆,为什么是 namespace需要查找cout ?还有没有cout可能会导致名称冲突的地方?如果有人可以为此提供图表,那就太好了。

另外,还有一些历史背景:

  1. iostream.h 到底是什么?在更改为 iostream 之前?

  2. 做了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/

相关文章:

c++ - 如何使用 boost::regex 进行多次替换

c++ - 查询可用内存量

c++ - 带有 initializer_list<Edge> C++ 的图形 - 如何在没有 "Edge"字的 initializer_list 处创建边?

c++ - 如何使用 std::enable_if 有条件地选择可变参数构造函数?

c++ - std::transform 与 std::for_each 不同吗?

Ruby 子类命名空间与父类

c# - 在静态类中定义的类的约束

c++ - 如果我在返回后声明它,存储数组在哪里?

c++ - 如何防止 std::string 使用 initializer_list 构造函数?

php - 带有闭包的意外 namespace 行为