cout和std::cout都相同,但是唯一的区别是,如果我们使用cout,则必须在程序中使用命名空间std,或者如果您不使用std命名空间,则应该使用std::cout。
cout是ostream类的预定义对象,用于在标准输出设备上打印数据(消息和值)。
通常,当我们在Linux操作系统中为GCC编译器编写程序时,它需要在程序中使用“ std”命名空间。
我们通过使用命名空间std来编写它;那么我们可以不使用std而访问任何对象,例如cout,cin,但是如果我们不使用命名空间std;那么我们应该使用std::cout等来防止错误。
我们可以将多个类封装到单个命名空间中。在这里,std是一个命名空间,:: :(作用域解析运算符)用于访问命名空间的成员。而且我们在C ++程序中包含了命名空间std,因此无需将std ::显式放入程序中即可使用cout和其他相关内容。
1)使用“使用命名空间标准”的程序–无错误
#include <iostream>
using namespace std;
int main(){
cout<<"Hi there, how are you?"<<endl;
return 0;
}
输出结果
Hi there, how are you?
2)不使用“使用命名空间std”和“ std ::”的程序–将会发生错误
#include <iostream>
int main(){
cout<<"Hi there, how are you?"<<endl;
return 0;
}
输出结果
cout<<"Hi there, how are you?"<<endl;
^
main.cpp:6:2: note: suggested alternative:
In file included from main.cpp:1:0:
/usr/include/c++/4.8.2/iostream:61:18: note: 'std::cout'
extern ostream cout; ///链接到标准输出
^
main.cpp:6:34: error: 'endl' was not declared in this scope
cout<<"Hi there, how are you?"<<endl;
^
main.cpp:6:34: note: suggested alternative:
In file included from /usr/include/c++/4.8.2/iostream:39:0,
from main.cpp:1:
/usr/include/c++/4.8.2/ostream:564:5: note: 'std::endl'
endl(basic_ostream<_CharT, _Traits>& __os)
3)无需使用“使用命名空间std”和使用“ std ::”的程序–无错误
#include <iostream>
int main(){
std::cout<<"Hi there, how are you?"<<std::endl;
return 0;
}
输出结果
Hi there, how are you?
在这里,std ::将与cout和endl一起使用。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有