简体   繁体   English

转发定义和名称空间使用

[英]Forward Definitions and namespace using

I am wondering about the meaning of the following lines of code in a header file... 我想知道文件中以下代码行的含义...

Firstly I have the standard using which makes a class from a namespace visible to my code 首先,我有一个标准的using ,它使名称空间中的类对我的代码可见

using mynamespace::myclass;

and then a forward declaration of the same class: 然后是同一类的前向声明:

namespace mynamespace
{
    class myclass;
}

and finally the forward declaration of another class: 最后是另一类的前向声明:

class myclass2;

What are the subtle differences for the programmer when "using" and when "forward declaring"? “使用”和“向前声明”时,程序员的细微差别是什么? Which is more preferred when writing a header file? 编写文件时哪个更优选?

In order to forward-declare class, you don't need using directive, it is usually better just to use fully qualified name in the header: 为了向前声明类,您不需要using指令,通常最好在标头中使用完全限定的名称:

namespace mynamespace
{
    class myclass;
}

class A{
    mynamespace::myclass* ptr;

};

Also, as jrok noted, you can't use using to bring the symbol to the current scope before the actual (forward) declaration of the symbol. 另外,正如jrok所指出的,您不能使用using将符号带到当前作用域之前,再进行符号的实际(向前)声明。

The only thing using does is make the specified symbol available in the current scope. 唯一using的作用是使当前范围内提供指定的符号。 It is unrelated to forward declarations. 它与前向声明无关。

Note that the specified symbol has to be declared already, so if you use both you'll have to forward declare first and then bring it into the current scope. 请注意,必须已经声明了指定的符号,因此,如果同时使用这两个符号,则必须先进行声明,然后再将其带入当前范围。 Example: 例:

namespace mynamespace {
    class myclass;
}

namespace this_header_namespace {
    using mynamespace::myclass;
}

Your first alternative is not valid. 您的第一种选择无效。 You can only give a using-declaration after a forward-declaration 您只能在前向声明给出使用声明

namespace N { class C; } // OK, now we know that N::C exists

using N::C;              // OK, now we can type C whenever we mean N::C

A forward-declaration introduces a name, a using-declaration introduces an abbreviation of that name (ie you can leave out the namespace qualification). 前向声明引入一个名称,using-声明引入该名称的缩写(即,您可以忽略名称空间限定)。

Informal analogy with first and last names: a person will first be introduced, and only then will you get on a first name basis. 用名字和姓氏进行非正式类比:首先将介绍一个人,然后才以名字为基础。

As a guideline: never put using-declarations into the global scope inside header files . 原则上: 切勿将using-声明放在头文件内的全局范围内 This will introduce the shorthand into every translation unit that includes that header, and is likely to lead to name clashes. 这会将速记引入到包含该标题的每个翻译单元中,并且可能导致名称冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM