C ++使用关键字 [英] C++ using keyword
问题描述
使用关键字的两种用法有什么区别:
using boost :: shared_ptr;
和
using namespace boost;
解决方案
:: shared_ptr;
只包含
shared_ptr
c $ c> boost 命名空间。
这意味着你可以使用shared_ptr
而不用命名空间boost
来限定它。
它被称为使用声明。
使用命名空间boost;
包括
boost
命名空间中的所有符号在您当前的范围。
这意味着您可以使用boost
命名空间中的所有符号,而不必使用命名空间boost
限定它们。
它被称为 using指令。
为什么应该总是优先使用声明
c>
使用指令
?
(
使用声明
)并避免第二个(using指令
),因为第二个会导致命名空间污染通过在当前命名空间中引入可能巨大数量的名称,其中许多都是不必要的。不必要的名称的存在极大地增加了意外的名称冲突的可能性。
关于使用的引用
Herb Sutter
使用指令
:
c>使用指令作为疯狂的野蛮人的疯狂军队,在任何地方不分青红皂白地销毁,只要它的存在可以导致
意想不到的冲突,
What is the difference between these two usage of
using
keyword:using boost::shared_ptr;
and
using namespace boost;
解决方案using boost::shared_ptr;
Includes only the
shared_ptr
from theboost
namespace in your current namespace. This means you can use theshared_ptr
without qualifying it with namespaceboost
.It is called a using declaration.
using namespace boost;
Includes all the symbols in the
boost
namespace in your current scope. This means you can use all the symbols in theboost
namespace without qualifying them with namespaceboost
.It is called as using directive.
Why should you always prefer
using declaration
overusing directive
?It is always better to use the first(
using declaration
) and avoid the second(using directive
) because the second causes namespace pollution by bringing in potentially huge numbers of names in to the current namespace, many of which are unnecessary. The presence of the unnecessary names greatly increases the possibility of unintended name conflicts.To quote
Herb Sutter
on the usage ofusing directive
:I find it helpful to think of a
using directive
as a marauding army of crazed barbarians that sows indiscriminate destruction wherever it passes--something that by its mere presence can causeunintended conflicts,
even when you think you're allied with it.这篇关于C ++使用关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!