C++ 中的多命名空间声明
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3589204/
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
Multiple namespace declaration in C++
提问by Robert Mason
Is it legal to replace something like this:
替换这样的东西是否合法:
namespace foo {
namespace bar {
baz();
}
}
with something like this:
像这样:
namespace foo::bar {
baz();
}
?
?
回答by skimobear
You can combine namespaces into one name and use the new name (i.e. Foobar).
您可以将命名空间合并为一个名称并使用新名称(即 Foobar)。
namespace Foo { namespace Bar {
void some_func() {
printf("Hello World.");
}
}}
namespace Foobar = Foo::Bar;
int main()
{
Foobar::some_func();
}
回答by NuSkooler
Pre C++17:
C++17 之前:
No, it's not. Instead of a bunch of indented nested namespaces, it's certainly valid to put them on the same line:
不,这不对。将它们放在同一行上当然是有效的,而不是一堆缩进的嵌套命名空间:
namespace Foo { namespace Bar { namespace YetAnother {
// do something fancy
} } } // end Foo::Bar::YetAnother namespace
C++17 Update:
C++17 更新:
You can now nest namespaces more cleanly in C++17:
namespace Foo::Bar::YetAnother {
// do something even fancier!
}
回答by Adi Lester
For anyone wondering, the form namespace foo::bar
is supported since C++17. References:
对于任何想知道的人,namespace foo::bar
从 C++17 开始就支持该表单。参考:
回答by AnT
Qualified names, like something::someting_else
in C++ can only be used to refer to entities that have already been declared before. You cannot use such names to introduce something previously unknown. Even if the nested namespace was already declared before, extending that namespace is also considered as "introducing something new", so the qualified name is not allowed.
限定名称,就像something::someting_else
在 C++ 中一样,只能用于引用之前已经声明过的实体。你不能用这样的名字来介绍以前未知的东西。即使之前已经声明了嵌套命名空间,扩展该命名空间也被视为“引入新事物”,因此不允许使用限定名称。
You can use such names for defining functions previously declared in the namespace
您可以使用这样的名称来定义先前在命名空间中声明的函数
namespace foo {
namespace bar {
int baz();
}
}
// Define
int foo::bar::baz() {
/* ... */
}
but not declaring new namespaces of extending existing ones.
但不声明扩展现有命名空间的新命名空间。
回答by Porculus
No; it's a syntax error.
不; 这是一个语法错误。
回答by Dean Harding
Did you try it? Visual C++ gives me the following errors:
你试了吗?Visual C++ 给了我以下错误:
1>C:\...\foo.cpp(31): error C2061: syntax error : identifier 'bar'
1>C:\...\fooo.cpp(31): error C2143: syntax error : missing ';' before '{'
1>C:\...\foo.cpp(31):错误 C2061:语法错误:标识符 'bar'
1>C:\...\fooo.cpp(31):错误 C2143:语法错误:缺少 ' ;' 前 '{'
回答by Chubsdad
As per the grammar in $2.10, an identifier cannot have the token ":"
. So the name foo::bar
is ill-formed.
根据 $2.10 中的语法,标识符不能有 token ":"
。所以这个名字foo::bar
是格式错误的。