C ++名称解析 [英] C++ Name Resolution

查看:96
本文介绍了C ++名称解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对C ++中的namespaceusing有所了解,我想知道它们之间的区别,并弄清楚如何以最佳方式使用它.

I'm wondering a bit about the namespace and using in C++ basically I would like to know the differences and figure out how to use it in the best way.

据我所知,(至少)有三种方法可以解析类名,但我不确定如何在其中进行选择:

As I see it there are (at least) three ways to resolve a class name and I am not sure how to choose among them:

  1. using namespace <namespace>
  2. using <namespace>::<what_to_use>
  3. <namespace>::<what_to_use> <use_it>
  1. using namespace <namespace>
  2. using <namespace>::<what_to_use>
  3. <namespace>::<what_to_use> <use_it>

我想知道优点,特别是如果涉及一种或另一种方式的性能,只是语法上的和偏好的问题,或者还有其他我没有考虑的问题.

I would like to know the advantages especially if there are performance involved in one or the other way, if it's just syntactical and a matter of preference or if there are other things I haven't considered regarding this.

推荐答案

第一个是

First is an using namespace directive, it brings all the symbol names from the specified namespace in your current namespace, irrespective of whether you need/use them. Certainly undesirable.

第二个是 使用名称空间声明 .它仅将指定的符号名称带入当前的名称空间.优点是您不必每次都键入完全限定名称.

Second is using namespace declaration. It only brings the specified symbol name in your current namespace. Advantage is you don't have to type the fully qualified name everytime.

第三是符号的 完全限定名称 .缺点是您必须在使用该符号的任何地方键入完全限定的名称.

Third is an fully qualified names of the symbol. Disadvantage is that you have to type the fully qualified name everywhere you use the symbol.

很明显,第二个&第三是更合适的.两者中的任何一个都没有性能差异.唯一的区别是您键入的字符数量.只需根据您的编码标准指定的内容来选择.

Clearly, Second & Third are the more suitable ones. There is no performance difference in either of them. The only difference is the amount of characters you type in. Simply, choose either depending on what your coding standard specifies.


正如@Jerry指出的那样,将声明与ADL(依赖于参数的查找)结合使用会导致不良后果.
您可以在我的答案之一中找到详细的解释:


As @Jerry points out, using declaration in combination with ADL(Argument dependent lookup) can lead to undesirable effects.
You can find a detailed explanation in one of my answers:

有关Koenig查找如何与名称空间配合使用以及为什么它是一件好事的详细说明?

Detailed explanation on how Koenig lookup works with namespaces and why its a good thing?

部分下的
为什么批评Koenig算法?

这篇关于C ++名称解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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