应该包含哪些标头才能在 Linux 上的 c++ 代码中保留前缀 std::

What header(s) should be included to leave the prefix std:: in my c++ code on Linux?

本文关键字:代码 c++ 上的 保留 std 前缀 Linux 包含哪      更新时间:2023-10-16

我想在Linux操作系统上的c ++代码中使用没有std::的语句(例如cout而不是std::cout,map<>而不是std::map<>等)。执行它需要哪些标头?

正如评论者指出的那样:没有包含来做到这一点,你只需要像往常一样包含你的文件,然后写一个using namespace语句

#include <iostream> // cout
#include <map> // map
using namespace std; // bring this entire namespace into scope

但是;你应该注意,评论者已经指出,这是一个糟糕的想法,尤其是在头文件中。对于您需要编写的额外几个字符,您可以节省数小时的麻烦。如果你真的反对写std::,请考虑限制你这样做的范围

{
    // lots of console printing:
    using std::cout;
    cout << "";
    ...
}
// Now you'd need to write std::cout again

这是独立于操作系统的(Linux的解决方案与其他操作系统相同)

如果您有要引入默认命名空间的类,您可以使用 using 来为它们设置别名。 例如:

using std::cout;

您可以使用 using namespace 导入整个命名空间,但您需要首先阅读并理解"为什么using namespace std被认为是不好的做法?

这不是

#including 某个标题的问题,可以使用 using 命名空间语句省略显式命名空间。
如果你想省略(真的:将所有 std:: 命名空间项放入全局命名空间,这可能不是真正的好做法),你可以使用:

using namespace std;

通常在 #includes 之后,但在引用 std 内容的任何代码之前。