未命名命名空间优于静态? [英] Superiority of unnamed namespace over static?

查看:67
本文介绍了未命名命名空间优于静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How are unnamed namespaces superior to the static keyword?

推荐答案

你基本上是指C ++标准中的$ 7.3.1.1 / 2部分,

You're basically referring to the section $7.3.1.1/2 from the C++ Standard,


static关键字的使用是

命名空间范围中声明对象时不推荐使用;
未命名命名空间提供了一个优越的
替代。

The use of the static keyword is deprecated when declaring objects in a namespace scope; the unnamed-namespace provides a superior alternative.

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

Unnamed namespace is superior to static keyword, primarily because the keyword static applies only to the variables declarations and functions, not to the user-defined types.

以下代码在C ++中有效

The following code is valid in 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 */ };

所以解决方案是未命名命名空间,这是

So the solution is, unnamed-namespace, which is this,

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

希望解释为什么 unnamed-namespace 优于 static

另外请注意,static关键字的使用在声明对象在命名空间范围(根据标准)。

Also, note that use of static keyword is deprecated when declaring objects in a namespace scope (as per the Standard).

这篇关于未命名命名空间优于静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆