在命名空间中定义类

发布于 2024-07-15 06:42:22 字数 143 浏览 8 评论 0原文

有没有比这更简洁的方法来在命名空间中定义类:

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 技术交流群。

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

发布评论

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

评论(4

风吹过旳痕迹 2024-07-22 06:42:22

很接近了,如果需要,您可以在命名空间中转发声明该类,然后在外部定义它:

namespace ns {
    class A; // just tell the compiler to expect a class def
}

class ns::A {
    // define here
};

您不能做的是在没有成员的命名空间中定义该类,然后在命名空间之外再次定义该类。 这违反了单一定义规则(或类似的废话)。

You're close, you can forward declare the class in the namespace and then define it outside if you want:

namespace ns {
    class A; // just tell the compiler to expect a class def
}

class ns::A {
    // define here
};

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).

独自唱情﹋歌 2024-07-22 06:42:22

您可以这样做,但实际上并没有更简洁。

namespace ns {
    class A;
}

class ns::A {
};

或者

namespace ns {
    class B;
}

using ns::B;
class B {
};

You can do that, but it's not really more succint.

namespace ns {
    class A;
}

class ns::A {
};

Or

namespace ns {
    class B;
}

using ns::B;
class B {
};
倾城花音 2024-07-22 06:42:22

您应该阅读的部分是:

7.3.1.2 命名空间成员定义

3 命名空间中首先声明的每个名称都是该命名空间的成员。[...]

请注意术语 -- 声明,因此 D.Shawley(及其示例)是正确的。

The section you should be reading is this:

7.3.1.2 Namespace member definitions

3 Every name first declared in a namespace is a member of that namespace.[...]

Note the term -- declaration so D.Shawley (and his example) is correct.

壹場煙雨 2024-07-22 06:42:22

不,你不能。 引用 C++ 标准,第 3.3.5 节:

在所有命名或名称之外声明的名称
未命名的命名空间 (7.3)、块
(6.3)、乐趣 (8.3.5)、功能
定义(8.4)和类(条款
9) 具有全局命名空间范围

因此声明必须位于命名空间块内 - 定义当然可以位于其外部。

No you can't. To quote the C++ standard, section 3.3.5:

A name declared outside all named or
unnamed namespaces (7.3), blocks
(6.3), fun (8.3.5), function
definitions (8.4) and classes (clause
9) has global namespace scope

So the declaration must be inside a namespace block - the definition can of course be outside it.

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