在C ++中使用完全限定的名称 [英] Using fully qualified names in C++

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

问题描述

我是C ++的新手,我在需要它的项目中尝试并行学习该语言.我正在使用一个相当流行且稳定的开源库来完成很多繁重的工作.阅读该库的源代码,教程和代码示例后,我注意到它们在声明类型时始终使用完全限定的名称,这通常会导致非常长而冗长的行,其中包含许多:: .这被认为是C ++中的最佳实践吗?有其他解决方法吗?

I am a C++ newcomer, trying to learn the language in parallel as I work on a project that requires it. I am using a fairly popular and stable open source library to do a lot of heavy lifting. Reading through the source, tutorials and code samples for the library, I have noticed that they always use fully qualified names when declaring types, which often results in very long and verbose lines with lots of ::'s. Is this considered best practice in C++? Is there a different way to deal with this?

推荐答案

他们可能发现比回答尝试了示例代码但发现它不起作用的人的很多问题要容易得多,只是因为他们没有使用"所涉及的名称空间.

They may have found it easier than answering lots of questions from people who tried the example code and found it didn't work, just because they didn't "use" the namespaces involved.

实践各不相同-如果您正在处理具有大量不同库和名称冲突的大型项目,则可能希望始终如一地主动使用更多名称空间限定符,以便在添加新代码时不必去做旧代码更清楚地说明了它要使用的内容.

Practices vary - if you're working on a large project with lots of diverse libraries and name clashes, you may wish to proactively use more namespace qualifiers consistently so that as you add new code you won't have to go and make old code more explicit about what it's trying to use.

从风格上讲,有些人更喜欢确切地知道所指的是潜在地必须挖掘或遵循IDE的声明"功能(如果可用),而另一些人则喜欢简洁并仅在例外"是对尚未包含的名称空间的引用-具有更多的上下文相关性.

Stylistically, some people prefer knowing exactly what's being referred to to potentially having to dig around or follow an IDE "go to declaration" feature (if available), while other people like concision and to see fuller namespace qualification only on the "exceptional" references to namespaces that haven't been included - a more contextual perspective.

避免使用名称空间xxx"是很正常的.在头文件中,因为包含该头的客户端代码将无法将其关闭,并且该名称空间的内容将永久转储到其默认搜索空间"中.因此,如果您在标头中查看代码,这就是它们可能更明确的原因之一.与此相反,您可以在函数体之类的范围内(甚至在标头中)使用使用名称空间",并且不会影响其他代码.通常在实现文件中使用一个您希望成为翻译单元中最终文件的命名空间,将其编译为要链接到最终可执行文件或本身创建的翻译单元中的库或对象,可执行文件.

It's also normal to avoid having "using namespace xxx;" in a header file, as client code including that header won't be able to turn it off, and the contents of that namespace will be permanently dumped into their default "search space". So, if you're looking at code in a header that's one reason they might be more explicit. Contrasting with that, you can having "using namespace" inside a scope such as a function body - even in a header - and it won't affect other code. It's more normal to use an namespace from within an implementation file that you expect to be the final file in a translation unit, compiling up to a library or object that you'll link into the final executable, or perhaps a translation unit that itself creates the executable.

这篇关于在C ++中使用完全限定的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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