在命名空间中定义类
有没有比这更简洁的方法来在命名空间中定义类:
namespace ns { class A {}; }
我希望像 class ns::A {};
这样的东西可以工作,但可惜不行。
Is there a more succinct way to define a class in a namespace than this:
namespace ns { class A {}; }
I was hoping something like class ns::A {};
would work, but alas not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
很接近了,如果需要,您可以在命名空间中转发声明该类,然后在外部定义它:
您不能做的是在没有成员的命名空间中定义该类,然后在命名空间之外再次定义该类。 这违反了单一定义规则(或类似的废话)。
You're close, you can forward declare the class in the namespace and then define it outside if you want:
What you cannot do is define the class in the namespace without members and then define the class again outside of the namespace. That violates the One Definition Rule (or somesuch nonsense).
您可以这样做,但实际上并没有更简洁。
或者
You can do that, but it's not really more succint.
Or
您应该阅读的部分是:
请注意术语 -- 声明,因此 D.Shawley(及其示例)是正确的。
The section you should be reading is this:
Note the term -- declaration so D.Shawley (and his example) is correct.
不,你不能。 引用 C++ 标准,第 3.3.5 节:
因此声明必须位于命名空间块内 - 定义当然可以位于其外部。
No you can't. To quote the C++ standard, section 3.3.5:
So the declaration must be inside a namespace block - the definition can of course be outside it.