为什么我不能在类似这样的命名空间中声明一个类? [英] Why can't I forward-declare a class in a namespace like this?

查看:436
本文介绍了为什么我不能在类似这样的命名空间中声明一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Namespace::Class;

为什么要这样做?:

namespace Namespace {
    class Class;
}

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

Using VC++ 8.0, the compiler issues:


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

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.

一旦你达到定义预先声明的类,你不需要再次重新打开命名空间。您可以在全局命名空间(或任何包含您的命名空间)的命名空间中定义为

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 :: Class

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

这篇关于为什么我不能在类似这样的命名空间中声明一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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