C++ 在命名空间中定义类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/623903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:21:16  来源:igfitidea点击:

Defining a class within a namespace

c++classsyntaxnamespacesdefinition

提问by D.Shawley

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.

我希望类似的东西class ns::A {};会起作用,但可惜没有。

回答by D.Shawley

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

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

回答by Logan Capaldo

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 {
};

回答by dirkgently

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.[...]

7.3.1.2 命名空间成员定义

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

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

注意这个词——声明,所以 D.Shawley(和他的例子)是正确的。

回答by dirkgently

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

不,你不能。引用 C++ 标准,第 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

在所有命名或未命名命名空间 (7.3)、块 (6.3)、fun (8.3.5)、函数定义 (8.4) 和类(第 9 条)之外声明的名称具有全局命名空间范围

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

所以声明必须在命名空间块内——定义当然可以在它之外。