Why can#39;t I forward-declare a class in a namespace using double colons?(为什么我不能使用双冒号在命名空间中前向声明一个类?)
问题描述
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.
这篇关于为什么我不能使用双冒号在命名空间中前向声明一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能使用双冒号在命名空间中前向声明一个类?
- 如何对自定义类的向量使用std::find()? 2022-11-07
- Stroustrup 的 Simple_window.h 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
