在命名空间中前向声明类
我很惊讶地发现我无法使用范围解析运算符从另一个范围转发声明一个类,即
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能在其名称空间之外声明类,因为编译器无法识别 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.
似乎答案就在 C++ 规范中:
Seems as though the answer lies in the C++ specification:
我不知道为什么。也许是因为,在您的第一个代码片段中,
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.