gpt4 book ai didi

c++ - std::cout 声明如何工作?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:25:37 24 4
gpt4 key购买 nike

std::cout对象在 iostream 中声明头文件为

namespace std _GLIBCXX_VISIBILITY(default)
{
...
extern ostream cout;
...
}

从现在开始,我将删除 std::前缀。

因此,据我了解,cout “只是”一个 ostream 类型的对象.我开始想知道为什么用 cout 将东西打印到屏幕上而不是与其他ostream对象,所以我尝试创建一个 ostream 类型的对象,但编译器不允许我这样做。事实上,ostream只是 basic_ostream<char> 的别名,并且该类型的默认构造函数受到保护。好吧,我想。但后来我想知道:为什么cout的声明是合法开始?为什么不发出编译器错误?

我再次尝试声明 ostream使用关键字 extern , 比如

extern ostream os;
os << "Will you compile?\n";

这次我得到了 os. 的 undefined reference 错误。然后问题就转移到以下内容:是否有 cout 的“定义”?别的地方?如果有,在哪里?

我无法理解这个问题。我知道,出于性能和安全原因,标准 header 是以一种“神秘”的方式编写的,除非您完全掌握该语言(我仍然不太可能),否则并不总是易于阅读,但我'我想了解这一点。

谢谢。

最佳答案

I started to wonder why stuff is printed to screen with cout and not with other ostream objects,

因为 std::cout 使用与 stdout 设备关联的流缓冲区。

so I tried to create an object of type ostream, but the compiler would not let me. As a matter of fact, ostream is just an alias for basic_ostream, and the default constructor for that type is protected. Fine, I thought. But then I wondered: why is the declaration of cout legal to start with? Why doesn't that issue a compiler error?

因为它是声明,而不是定义,所以它不调用任何构造函数。也许您应该了解 extern 在声明中的含义。

带有extern 的声明只是表示在程序的其他地方定义了一个类型为ostream 并称为cout 的对象。由于您实际上没有提供任何此类定义,因此您会收到链接器错误。

要近似模拟 std::cout,您可以在一些 .cpp 文件中执行此操作:

namespace {
std::ofstream fake_cout("/dev/stdout");
}
std::ostream cout(fake_cout.rdbuf());

这将创建一个写入 /dev/stdoutfstream 然后将名为 coutostream 与其相关联流缓冲区。

这不是对真实 std::cout 的良好模拟,因为它不能确保流在任何其他全局变量尝试使用它之前被初始化,而真实的会这样做。

关于c++ - std::cout 声明如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33110526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com