在命名空间中前向声明类

发布于 2024-09-10 14:18:58 字数 266 浏览 7 评论 0原文

我很惊讶地发现我无法使用范围解析运算符从另一个范围转发声明一个类,即

class someScope::someClass;

相反,必须按如下方式使用完整声明:

namespace
{
    class someClass;
}

有人可以解释为什么会出现这种情况吗?

更新:为了澄清,我想问为什么会出现这种情况。

I was rather surprised to learn that I couldn't forward declare a class from another scope using the scope resolution operator, i.e.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

缱绻入梦 2024-09-17 14:18:58

您不能在其名称空间之外声明类,因为编译器无法识别 someScope 的类型。

需要 namespace{ } 来声明名称空间的存在,然后将 class someClass 声明到您的作用域中。

You can't declare a class outside its namespace, because the compiler could not be aware of the type of someScope.

namespace{ } is required to declare the existence of namespace, and then, declare class someClass into your scope.

ぽ尐不点ル 2024-09-17 14:18:58

似乎答案就在 C++ 规范中:

3.3.5 标准中的“命名空间范围”。

在命名空间主体中声明的实体
据说是该组织的成员
命名空间和引入的名称
这些声明纳入
命名空间的声明区域
据说是成员的名字
命名空间。

命名空间成员也可以是
在 :: 范围之后引用
解析算子(5.1)应用于
其命名空间的名称或名称
命名空间的
a 中成员的命名空间
使用指令;

Seems as though the answer lies in the C++ specification:

3.3.5 "Namespace scope" in the standard.

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.

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;

合约呢 2024-09-17 14:18:58

我不知道为什么。也许是因为,在您的第一个代码片段中, someScope 未声明。它可以是命名空间,也可以是类名。如果 someScope 是类名,则不能独立转发声明另一个类的类成员。

I am not sure why. Maybe because, in your first code snippet, someScope is undeclared. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文