Why is quot;using namespace std;quot; considered bad practice?(为什么是“使用命名空间标准?被认为是不好的做法?)
问题描述
其他人告诉我,在代码中编写 using namespace std; 是错误的,我应该使用 std::cout 和 std::cin 直接代替.
I've been told by others that writing using namespace std; in code is wrong, and that I should use std::cout and std::cin directly instead.
为什么 using namespace std; 被认为是一种不好的做法?它是效率低下还是有声明不明确变量的风险(与 std 命名空间中的函数具有相同名称的变量)?它会影响性能吗?
Why is using namespace std; considered a bad practice? Is it inefficient or does it risk declaring ambiguous variables (variables that share the same name as a function in std namespace)? Does it impact performance?
推荐答案
这与性能完全无关.但是考虑一下:您正在使用两个名为 Foo 和 Bar 的库:
This is not related to performance at all. But consider this: you are using two libraries called Foo and Bar:
using namespace foo;
using namespace bar;
一切正常,您可以毫无问题地从 Foo 调用 Blah() 和从 Bar 调用 Quux().但是有一天你升级到 Foo 2.0 的新版本,它现在提供了一个名为 Quux() 的函数.现在你遇到了一个冲突:Foo 2.0 和 Bar 都将 Quux() 导入到你的全局命名空间中.这需要一些努力来解决,尤其是在函数参数恰好匹配的情况下.
Everything works fine, and you can call Blah() from Foo and Quux() from Bar without problems. But one day you upgrade to a new version of Foo 2.0, which now offers a function called Quux(). Now you've got a conflict: Both Foo 2.0 and Bar import Quux() into your global namespace. This is going to take some effort to fix, especially if the function parameters happen to match.
如果你曾经使用过foo::Blah()和bar::Quux(),那么引入foo::Quux() 将是一个非事件.
If you had used foo::Blah() and bar::Quux(), then the introduction of foo::Quux() would have been a non-event.
这篇关于为什么是“使用命名空间标准"?被认为是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么是“使用命名空间标准"?被认为是不好的做法?
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
