std::cout 在哪里定义的?

Where is std::cout defined?

我想知道它是如何工作的...

<iostream>header中有namespace std:

#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>

namespace std {
  extern istream cin;
  extern ostream cout;
  extern ostream cerr;
  extern ostream clog;
  extern wistream wcin;
  extern wostream wcout;
  extern wostream wcerr;
  extern wostream wclog;
}

因此,cout 是类型 ostream 的 object 的名称,它是在另一个文件中定义的(由于 extern)。好的

当我在我的简单程序中尝试创建一个 ostream object 时,我不能,因为 ostream class 的构造函数是 protected.好的

那么,如何在外部文件中创建(定义)一个 object,它有一个 protected 构造函数,看起来像一个全局变量?

gcc使用的libstdc++是怎么做的:

cout 的存储被定义为 fake_ostream 类型的全局变量,据推测可以毫无问题地构造它。 https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/src/c%2B%2B98/globals_io.cc

然后在库初始化期间使用显式构造函数重写了一个新的放置。 https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/src/c%2B%2B98/ios_init.cc

其他编译器有自己的库,可能会使用不同的技巧。检查 clang 使用的 libc++ 源作为 reader.

的练习