为什么我不能使用双冒号在命名空间中前向声明一个类?

2022-01-14 00:00:00 namespaces c++
class Namespace::Class;

为什么我必须这样做?:

Why do I have to do this?:

namespace Namespace {
    class Class;
}

使用VC++ 8.0,编译器问题:

Using VC++ 8.0, the compiler issues:

错误 C2653:命名空间":不是类或命名空间名称

error C2653: 'Namespace' : is not a class or namespace name

我认为这里的问题是编译器无法判断 Namespace 是类还是命名空间?但是为什么这很重要,因为它只是一个前向声明?

I assume that the problem here is that the compiler cannot tell whether Namespace is a class or a namespace? But why does this matter since it's just a forward declaration?

还有其他方法可以前向声明在某个命名空间中定义的类吗?上面的语法感觉就像我正在重新打开"命名空间并扩展它的定义.如果 Class 实际上没有在 Namespace 中定义怎么办?这会在某个时候导致错误吗?

Is there another way to forward-declare a class defined in some namespace? The syntax above feels like I'm "reopening" the namespace and extending its definition. What if Class were not actually defined in Namespace? Would this result in an error at some point?

推荐答案

因为你不能.在 C++ 语言中,完全限定名称仅用于引用 现有(即先前声明的)实体.它们不能用于引入新实体.

Because you can't. In C++ language fully-qualified names are only used to refer to existing (i.e. previously declared) entities. They can't be used to introduce new entities.

而您正在实际上重新打开"命名空间以声明新实体.如果类 Class 稍后被定义为不同命名空间的成员 - 它是一个完全不同的类,与您在此处声明的类无关.

And you are in fact "reopening" the namespace to declare new entities. If the class Class is later defined as a member of different namespace - it is a completely different class that has nothing to do with the one you declared here.

一旦你到了定义预先声明的类的地步,你就不需要再次重新打开"命名空间了.您可以在全局命名空间(或包含 Namespace 的任何命名空间)中将其定义为

Once you get to the point of defining the pre-declared class, you don't need to "reopen" the namespace again. You can define it in the global namespace (or any namespace enclosing your Namespace) as

class Namespace::Class {
  /* whatever */
};

由于您指的是已在命名空间 Namespace 中声明的实体,因此您可以使用限定名称 Namespace::Class.

Since you are referring to an entity that has already been declared in namespace Namespace, you can use qualified name Namespace::Class.

相关文章