cout是ostream类的一个预定义对象,它被用来在标准输出设备上打印数据。一般来说,当我们在Linux操作系统中为G++编译器编写程序时,它需要在程序中使用 stdc命名空间。
// 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"<
在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 中计算 |