这是我的代码:
#include <iostream>
int main()
{
int32_t i = 5;
std::cout << "i: " << i << '\n';
}
这是输出:
$ clang++ -std=c++11 -pedantic -Wall -Wextra foo.cpp && ./a.out
i: 5
这是我的问题:
C++ 标准似乎在 std
命名空间内的 cstdint
中定义了 int32_t
。
在我的代码中,我既没有包含 cstdint
也没有使用 std
命名空间。为什么编译器不报错?
最佳答案
名字int32_t
也出现在 C 库头文件的全局范围内 stdint.h
.这可能使它在 C++ 中也全局可见。
本节[Headers]说:
... the contents of each header cname is the same as that of the corresponding header name.h as specified in the C standard library. In the C++ standard library, however, the declarations (except for names which are defined as macros in C) are within namespace scope of the namespace std. It is unspecified whether these names (including any overloads added in [language.support] through [thread] and [depr]) are first declared within the global namespace scope and are then injected into namespace std by explicit using-declarations.
标准还有a blanket statement :
A C++ header may include other C++ headers.
所以通过包含 <iostream>
您可以保证看到流对象,但也可能碰巧访问一些其他库功能。
由于这些间接包含未指定,因此结果因实现而异。因此程序应该始终包含它需要的所有头文件,以便移植到不同的编译器。
关于c++ - 在不使用 std 的情况下如何使用 int32_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50505212/