Welcome
admin
admin

2026-02-09 16:11:55

世界杯误判
4885 784

cout和std::cout都相同,但是唯一的区别是,如果我们使用cout,则必须在程序中使用命名空间std,或者如果您不使用std命名空间,则应该使用std::cout。

什么是cout?cout是ostream类的预定义对象,用于在标准输出设备上打印数据(消息和值)。

cout带有和不带有std的用法通常,当我们在Linux操作系统中为GCC编译器编写程序时,它需要在程序中使用“ std”命名空间。

我们通过使用命名空间std来编写它;那么我们可以不使用std而访问任何对象,例如cout,cin,但是如果我们不使用命名空间std;那么我们应该使用std::cout等来防止错误。

我们可以将多个类封装到单个命名空间中。在这里,std是一个命名空间,:: :(作用域解析运算符)用于访问命名空间的成员。而且我们在C ++程序中包含了命名空间std,因此无需将std ::显式放入程序中即可使用cout和其他相关内容。

1)使用“使用命名空间标准”的程序–无错误

代码语言:javascript复制#include

using namespace std;

int main(){

cout<<"Hi there, how are you?"<

return 0;

}输出结果

代码语言:javascript复制Hi there, how are you?2)不使用“使用命名空间std”和“ std ::”的程序–将会发生错误

代码语言:javascript复制#include

int main(){

cout<<"Hi there, how are you?"<

return 0;

}输出结果

代码语言:javascript复制 cout<<"Hi there, how are you?"<

^

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?"<

^

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 ::”的程序–无错误

代码语言:javascript复制#include

int main(){

std::cout<<"Hi there, how are you?"<

return 0;

}输出结果

代码语言:javascript复制Hi there, how are you?在这里,std ::将与cout和endl一起使用。