为什么我需要做'using namespace std'而不是"使用 std::cout"?
Why do I need to do 'using namespace std' instead of 'using std::cout'?
everyone. 我了解到,为了避免命名空间冲突,通常需要使用std::cout
而不是using namespace std
编写代码。在下面的脚本中,我只使用 cout,如果我写 std:: cout 而不是使用命名空间 std;它不起作用。 谁能帮我理解为什么?一般来说,std::cout
什么时候不起作用,我被迫使用using namespace std
?
#include <iostream>
#include <string>
using std::cout; //if writing here "using namespace std;" instead, the code does not work
class MyClass{
public:
string name;
MyClass (string n)
{
name=n;
cout<<"Hello "<<name;
}
};
int main()
{
MyClass MyObj("Mike");
return 0;
}
您需要添加using std::string;
以及using std::cout;
才能使其正常工作,因为您不仅使用来自命名空间 std 的 cout,string
还是您在代码中使用的namespace std
的成员。
您的代码适用于:
using std::cout;
语句cout
,但编译器也必须知道您当前正在使用的string
的位置(实际上它是std::string
(。您必须定义:
using std::string;
当您输入时:
using namespace std;
它调用名为std
的整个命名空间,其中包含作为标准库添加的各种功能C++然后您无需对该命名空间的那些函数/类/变量使用前缀std::
。
相关文章:
- std::cout.imbue()多重调用
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- std::cout输出int时出现编译错误
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- main() 中的 std::cout 在调试期间不会在调试控制台中打印任何内容
- std::cout 来自多个线程
- 在 c++ 中以十六进制格式打印无符号字符(BYTE).使用 std::cout
- Cuda 基本程序 (将值写入矩阵和 std:cout 不起作用) ;主功能不启动
- 是否可以为 std::cout 创建别名?
- std::cout 在打印变量与函数表达式时的行为不同
- 带有 std::cout 的多线程控制台文本动画
- 捕获/禁止发送到 std::cout 的 OpenCV 警告
- printf() 和 std::cout 在指针方面的区别
- 使用字符串流加速 std::cout 日志记录
- 是否可以在每次使用std::cout时执行一个函数
- 为什么'std::cout << !+2 '输出 0?
- 如何将自定义类传递给std::cout
- 对于输出,std::copy是否比std::cout快