开发者

cout (standard output) in C++

开发者 https://www.devze.com 2023-01-27 12:45 出处:网络
// my first prog开发者_如何学Cram in C++ #include <iostream> using namespace std; int main ()
// my first prog开发者_如何学Cram in C++

#include <iostream>
using namespace std;

int main ()
{
  cout << "Hello World!";
  return 0;
}

Is cout an object? If so, where is it instantiated? (I don't see something like "new ....")


cout is a global object declared somewhere in <iostream>.

By the way, unlike in Java or C#, you don't need new to create an object. For instance, this will work:

std::string str; // creates a new std::string object called "str"


The current C++ standard states (27.3/2):

[...]The objects are constructed, and the associations are established at some time prior to or during first time an object of class ios_base::Init is constructed, and in any case before the body of main begins execution. The objects are not destroyed during program execution.

And from ([iostream.objects]/2:

If a translation unit includes <iostream> or explicitly constructs an ios_base::Init object, these stream objects shall be constructed before dynamic initialization of non-local objects defined later in that translation unit."

In C++ parlance a translation-unit is nothing but a compiler terminology for a file and any/all headers which are included into that file.


Yes, it is initialize by C++ runtime library when your program startup.


cout is an object. It's instantiated by the implementation during the startup of your program. That means that it can happen in the CRT DLL or in the code linked statically.


Yes, cout is an object. It's instantiated in <iostream> header file behind your back (together with some other streaming objects like cin or cerr) :)


Cout is part of the library you just instantiated in the header IOSTREAM.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号