问题描述
使用声明的两种方法是
using std::string; using std::vector;
或
using namespace std;
哪种方式更好?
========满意的回答下面=============
=========Satisfactory Answer Below=============
简而言之,在本地使用函数中的声明是无害的
In short, using declarations within functions are harmless provided locally scoped care is given whereas global using declarations are dangerous as they could cause namespaces to intersect, thereby confusing the compiler.
感谢Jonathan Wakely的报价。
Credit to Jonathan Wakely for the quote.
推荐答案
这取决于。
name使用声明更好,例如
If you want to inject a single name into another scope, the using-declaration is better, e.g.
namespace foolib { // allow vector to be used unqualified within foo, // or used as foo::vector using std::vector; vector<int> vec(); template<typename T> struct Bar { T t; }; template<typename T> void swap(Bar<T>& lhs, Bar<T>& rhs) { using std::swap; // find swap by ADL, otherwise use std::swap swap(lhs.t, rhs.t); } }
但有时候你只需要所有的名字,使用指令。
But sometimes you just want all names, which is what a using-directive does. That could be used locally in a function, or globally in a source file.
在函数外部使用命名空间放置身体应该只在你知道确切包含什么,所以它是安全的(即不在标题,你不知道将包括在标题之前或之后),但许多人仍然对此使用感到不满(请参阅):
Putting using namespace outside a function body should only be done where you know exactly what's being included so it's safe (i.e. not in a header, where you don't know what's going to be included before or after that header) although many people still frown on this usage (read the answers at Why is "using namespace std;" considered bad practice? for details):
#include <vector> #include <iostream> #include "foolib.h" using namespace foo; // only AFTER all headers Bar<int> b;
使用using-directive的一个好理由是,命名空间只包含少量的名称被有意隔离,并且被设计为由using-directive使用:
A good reason to use a using-directive is where the namespace only contains a small number of names that are kept intentionally segregated, and are designed to be used by using-directive:
#include <string> // make user-defined literals usable without qualification, // without bringing in everything else in namespace std. using namespace std::string_literals; auto s = "Hello, world!"s;
所以没有一个答案可以说一个普遍比另一个更好,他们有不同的用途
So there is no single answer that can say one is universally better than the other, they have different uses and each is better in different contexts.
关于使用命名空间的第一个用法,C ++的创建者Bjarne Stroustrup,在 (强调我的)的§14.2.3中有这样的说法:
Regarding the first usage of using namespace, the creator of C++, Bjarne Stroustrup, has this to say in §14.2.3 of The C++ Programming Language, 4th Ed (emphasis mine):
只是坚持它是坏的,不应该使用。
To me this seems far better advice than just insisting it is bad and should not be used.
这篇关于使用std ::< type> v.s.使用std命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!