简体   繁体   English

转发声明命名空间中的类

[英]Forward declaring classes in namespaces

I was rather surprised to learn that I couldn't forward declare a class from another scope using the scope resolution operator, ie 我很惊讶地发现我无法使用范围解析运算符从另一个范围转发声明一个类,即

class someScope::someClass;

Instead, the full declaration has to be used as follows: 相反,必须使用完整声明如下:

namespace
{
    class someClass;
}

Can someone explain why this is the case? 有人可以解释为什么会这样吗?

UPDATE: To clarify, I am asking why this is the case. 更新:澄清一下,我在问为什么会这样。

You can't declare a class outside its namespace, because the compiler could not be aware of the type of someScope . 您不能在其命名空间之外声明一个类,因为编译器无法知道someScope的类型。

namespace{ } is required to declare the existence of namespace, and then, declare class someClass into your scope. namespace {}需要声明命名空间的存在,然后将someClass类声明到您的范围中。

Seems as though the answer lies in the C++ specification: 似乎答案在于C ++规范:

3.3.5 "Namespace scope" in the standard. 3.3.5标准中的“命名空间范围”。

Entities declared in a namespace-body are said to be members of the namespace, and names introduced by these declarations into the declarative region of the namespace are said to be member names of the namespace. 在namespace-body中声明的实体被称为命名空间的成员,并且这些声明引入命名空间的声明性区域的名称被称为命名空间的成员名称。

A namespace member can also be referred to after the :: scope resolution operator (5.1) applied to the name of its namespace or the name of a namespace which nominates the member's namespace in a using-directive; 在应用于其命名空间名称的:: scope resolution运算符(5.1)或在using-directive中指定成员名称空间的名称空间名称之后,也可以引用名称空间成员。

I am not sure why. 我不知道为什么。 Maybe because, in your first code snippet, someScope is undeclared. 也许是因为,在你的第一个代码片段中, someScope是未声明的。 It can be a namespace, or a class name. 它可以是命名空间,也可以是类名。 If someScope is a class name, you can't independently forward declare a class member of another class. 如果someScope是类名,则不能独立转发声明另一个类的类成员。

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

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