cout函数在C++中是什么意思和和作用
cout是在iostrem文件中定义的全局对象,只要#include <iostream>就能生成此对象,便可直接使用。
C++和java的面对对象特性不同,java是纯面对对象语言,不能使用全局变量,所有的对象必须定义在类中,其实在System类初始化时就已经初始化了out对象,out对象是java.io.PrintStream类型的静态对象。
而C++是从C中延伸出来了,保留了面向过程编程的特性,能够定义全局变量,其实cout就相当于System.out对象。而且C++支持运算符重载,且ostream类重载了<<运算符,所以就能写成cout << var的形式。
下面是iostream文件的代码。
#if _MSC_VER > 1000
#pragma once
#endif
#ifndef _IOSTREAM_
#define _IOSTREAM_
#include <istream>
#ifdef _MSC_VER
#pragma pack(push,8)
#endif
_STD_BEGIN
static ios_base::Init _Ios_init;
extern _CRTIMP istream cin;
extern _CRTIMP ostream cout; // 就这句话
extern _CRTIMP ostream cerr, clog;
class _CRTIMP _Winit {
public:
_Winit();
~_Winit();
private:
static int _Init_cnt;
};
static _Winit _Wios_init;
extern _CRTIMP wistream wcin;
extern _CRTIMP wostream wcout, wcerr, wclog;
_STD_END
#ifdef _MSC_VER
#pragma pack(pop)
#endif
#endif