c++ - 在不使用 std 的情况下如何使用 int32_t?

标签 c++ c++11 types header namespaces

这是我的代码:

#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/

相关文章:

C++ 指向对象类型检查的指针

c++ Qt Qwt构建问题

c++ - 为什么在 main() 之前断言会导致语法错误 "error: expected ' )' before numeric constant"?

c++ - 插入已排序的 vector<unique_ptr<pair<>>> 时避免堆分配

boost::make_shared<T>(...) 不编译, shared_ptr<T>(new T(...)) 编译

c++ - 有没有办法将 void (*)(uint32_t, void (*)(uint32_t)) 转换为 std::function<void(uint32_t, std::function<void(uint32_t)>)>?

vector - 用任何类型的元组定义向量

c# - 数值类型的 "base class"是什么?

c++ - 内联函数返回不正确的结果

c++ - 在头文件中搜索#ifdef