为什么“使用命名空间标准"?被认为是不好的做法? [英] Why is "using namespace std;" considered bad practice?

查看:113
本文介绍了为什么“使用命名空间标准"?被认为是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其他人告诉我,用代码编写using namespace std;是错误的,我应该直接使用std::coutstd::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.

这篇关于为什么“使用命名空间标准"?被认为是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆