C++中 cout 和std cout的区别
世界杯实时直播 2995 2026-02-09 16:11:46

C++中 cout 和std cout的区别

cout 是 ostream 类的一个预定义对象,它被用来在标准输出设备上打印数据。一般来说,当我们在Linux操作系统中为G++编译器编写程序时,它需要在程序中使用 std c命名空间。

// Program to show the use of cout without using namespace

#include

int main()

{

std::cout << "YiibaiForGeeks";

return 0;

}

std:cout: 命名空间是一个声明性的区域,里面定义了一些东西。所以,在这种情况下, cout 被定义在std命名空间中。因此, std::cout 说明 cout 定义在std命名空间,否则就使用定义在 std 命名空间的 cout 的定义。因此, std::cout 被用于定义 std 命名空间中的 cout 。

// Program to show use of using namespace

#include

using namespace std;

int main()

{

cout << "YiibaiForGeeks";

return 0;

}

如果 cout 既不使用 “using namespace std “也不使用 “std::”,会发生什么?

// Program without using

// using namespace std and std::

#include

int main()

{

cout << "YiibaiForGeeks";

return 0;

}

编译错误 –

main.cpp: In function ‘int main()’:

main.cpp:5:2: error:

‘cout’ was not declared in this scope

cout<<"YiibaiForGeeks"<

main.cpp:5:2: note: suggested alternative:

In file included from main.cpp:1:0:

/usr/include/c++/7/iostream:61:18: note: `std::cout`

extern ostream cout; /// Linked to standard output

在C++中, cout 和 std::cout 都是一样的,但有一些基本区别如下 –

编号

cout

std::cout

1

必须在程序中写入 namespace std

如果之前没有声明 namespace std ,则必须使用 std::cout

2

cout 是 ostream 类的预定义对象

std::cout 调用标准模板/Iostream库,因为 cout 只在 std 命名空间中定义。

3

事先声明命名空间,就可以访问许多函数,如 cin 、 cout 等。

这只是在函数中对 std 库进行的隐式初始化,如在 main 中计算

Copyright © 2022 98世界杯_乌拉圭世界杯 - cy078.com All Rights Reserved.