简体   繁体   English

std::cout 如何知道在哪里打印?

[英]How does std::cout know where to print?

Why does a terminal window open when I run my C++ program, and how does std::cout know that it's supposed to print to that terminal?当我运行 C++ 程序时,为什么终端 window 会打开, std::cout如何知道它应该打印到该终端?

Every operating system has what is called a "standard output stream", when you use cout, c++ just tells the operating system to print to the stream.每个操作系统都有所谓的“标准 output 流”,当您使用 cout 时,c++ 只是告诉操作系统打印到 stream。 The operating system is what figures out where to output it.操作系统是找出 output 的位置。

The compiler recognises that you're writing a console based application and provides a runtime environment suited to the type of program you're writing.编译器识别出您正在编写基于控制台的应用程序,并提供适合您正在编写的程序类型的运行时环境。

The type of application is usually selected when you start a new project but in older compilers, the console type was the only type that was available.启动新项目时通常会选择应用程序的类型,但在较旧的编译器中,控制台类型是唯一可用的类型。 MS-DOS and CP/M provided terminal services, upon which the command line interpreter like "command.com" would be the default program that could call other programs like "myCppApp.exe". MS-DOS 和 CP/M 提供终端服务,命令行解释器如“command.com”将是默认程序,可以调用其他程序如“myCppApp.exe”。

The terminal services included an input stream (what you typed at the keyboard) and an output stream (what was displayed on the screen).终端服务包括输入 stream(您在键盘上键入的内容)和 output stream(显示在屏幕上的内容)。 These were treated as special files which were readonly (cin) and writeonly (cout).这些被视为只读(cin)和只写(cout)的特殊文件。

C/C++ provided access to these standard disk operating system services by way of cin/cout. C/C++ 通过 cin/cout 提供了对这些标准磁盘操作系统服务的访问。

When windows came along, rather than use the text console (which you can still see on some computers when they boot up or in BIOS settings) people preferred to use virtual console windows that emulated the text console within a graphical user interface.当 windows 出现时,人们宁愿使用在图形用户界面中模拟文本控制台的虚拟控制台 windows,而不是使用文本控制台(您仍然可以在某些计算机启动时或在 BIOS 设置中看到)。

So its kind of a combination of the operating system providing a pretend environment and the compiler providing a runtime code based on the fact your building a console application.因此,它是一种提供假装环境的操作系统和基于您构建控制台应用程序的事实提供运行时代码的编译器的组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM