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

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

问题描述

其他人告诉我,在代码中编写 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.

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

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