April 22th Wednesday (四月 二十二日 水曜日)

本文探讨了C++中使用指令与使用声明的区别。详细解释了两者在名称解析上的不同行为,以及未命名名称空间的作用和限制。通过具体示例说明如何避免名称冲突并保持代码清晰。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 Using-Directive Versus Using-Declaration

  Using a using-directive to import all the names wholesale is not the same as using multiple using-declarations. It's more like the mass
application of a scope resolution operator. When you use a using-declaration, it is as if the name is declared at the location of the
using-declaration. If a particular name already is declared in a function, you can't import the same name with a using-declaration. When
you use a using-directive, however, name resolution takes place as if you declared the names in the smallest declarative region containing
both the using-declaration and the namespace itself.

Remember

  Suppose a namespace and a declarative region both define the same name. If you attempt to use a using-declaration to bring the namespace
name into the declarative region, the two names conflict, and you get an error. If you use a using-directive to bring the namespace name into
the declarative region, the local version of the name hides the namespace version.

Unnamed Namespaces

  You can create an unnamed namespace by omitting the namespace name:

namespace        // unnamed namespace
{
    int ice;
    int bandycoot;
}

  This behaves as if it were followed by a using-directive; that is, the names declared in this namespace are in potential scope until the end
of the declarative region containing the unnamed namespace. In this respect, they are like global variables. However, because the namespace has
no name, you can't explicitly use a using-directive or using-declaration to make the names available elsewhere. In particular, you can't use names
from an unnamed namespace in a file other than the one containing the namespace declaration. This provides an alternative to using static variables
with internal linkage. Indeed, the C++ standard deprecates the use of the keyword static in namespaces and global scope. ("Deprecate" is a term
the standard uses to indicate practices that currently are valid but most likely will be rendered invalid by future revisions of the standard.)
Suppose, for example, you have this code:

static int counts;   // static storage, internal linkage
int other();
int main()
{
}
int other()
{
}

  The intent of the standard is that you should do this instead:

namespace
{
    int counts;   // static storage, internal linkage
}
int other();
int main()
{
}
int other()
{
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值