为什么我不能使用双冒号在名称空间中向前声明一个类? [英] Why can't I forward-declare a class in a namespace using double colons?

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

问题描述

class Namespace::Class;

我为什么要这样做?:

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 ++语言中,完全限定的名称仅用于引用现有(即先前声明的)实体.它们不能用于引入 new 实体.

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.

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

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