gpt4 book ai didi

c++ - 未命名命名空间优于静态命名空间?

转载 作者:IT老高 更新时间:2023-10-28 11:51:59 29 4
gpt4 key购买 nike

未命名的命名空间如何优于 static 关键字?

最佳答案

您基本上是指 C++03 标准中的第 7.3.1.1/2 节,

The use of the static keyword isdeprecated when declaring objects in anamespace scope; theunnamed-namespace provides a superioralternative.

请注意,该段落已在 C++11 中删除。 static 函数已按标准不再被弃用!

不过,未命名的 namespace 优于 static 关键字,主要是因为关键字 static 仅适用于 variables 声明和函数,而不是用户定义的类型

以下代码在 C++ 中有效:

//legal code
static int sample_function() { /* function body */ }
static int sample_variable;

但此代码无效:

//illegal code
static class sample_class { /* class body */ };
static struct sample_struct { /* struct body */ };

所以解决方案是,未命名(又名匿名)namespace,就是这样:

//legal code
namespace
{
class sample_class { /* class body */ };
struct sample_struct { /* struct body */ };
}

希望它能解释为什么未命名的 namespace 优于 static

<罢工>另外,请注意,在命名空间范围内声明对象时(根据标准),不推荐使用 static 关键字。

关于c++ - 未命名命名空间优于静态命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4422507/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com