gpt4 book ai didi

c++ - 在带或不带命名空间的 中使用类型

转载 作者:可可西里 更新时间:2023-11-01 15:52:28 24 4
gpt4 key购买 nike

在 C++11 中,我可以选择是否要使用在有或没有命名空间 std::中定义的类型

至少我的编译器 (g++ 4.7) 接受这两种变体。

我的问题是:使用 cstdint 中的 typedef 的推荐方法是什么。有或没有命名空间?有什么优点或缺点?还是只是风格问题?

所以变体 a):

#include <cstdint>
std::uint8_t n = 21;

回复:

#include <cstdint>
using std::uint8_t;
uint8_t n = 21;

或变体 b):

#include <cstdint>
uint8_t n = 21;

最佳答案

首选在 std 中声明的名称命名空间。原因在 §17.6.1.3/4(ISO/IEC 14882:2011(E),C++11)中给出:

Except as noted in Clauses 18 through 30 and Annex D, the contents of each header cname shall be the same as that of the corresponding header name.h, as specified in the C standard library (1.2) or the C Unicode TR, as appropriate, as if by inclusion. In the C++ standard library, however, the declarations (except for names which are defined as macros in C) are within namespace scope (3.3.6) of the namespace std. It is unspecified whether these names are first declared within the global namespace scope and are then injected into namespace std by explicit using-declarations (7.3.3).

如果您使用来自 <c 的名称姓名 >标题没有 std ,您的程序依赖于未指定的要求。

这在 C++03 和更早版本中有所不同,名称只应该出现在 std 中命名空间。然而,现实是许多实现只是简单地注入(inject) C 标准库头文件的内容 < 姓名 .h>进入std所以这在 C++11 中得到了适应。 C++03 标准的相应部分 (§17.4.1.2/4) 说:

Except as noted in clauses 18 through 27, the contents of each header cname shall be the same as that of the corresponding header name.h, as specified in ISO/IEC 9899:1990 Programming Languages C (Clause 7), or ISO/IEC:1990 Programming Languages—C AMENDMENT 1: C Integrity, (Clause 7), as appropriate, as if by inclusion. In the C++ Standard Library, however, the declarations and definitions (except for names which are defined as macros in C) are within namespace scope (3.3.5) of the namespace std.

此外,使用 std:: 限定名称有助于避免碰撞——如果你完全符合条件,你就会确切地知道你得到了什么。如果你真的要做 using namespace stdusing std::something ,至少在尽可能小的范围内进行。

关于c++ - 在带或不带命名空间的 <cstdint> 中使用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13129945/

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