【问题标题】:Is it possible to view all the contents of a namespace in c ++?是否可以在 C++ 中查看命名空间的所有内容?
【发布时间】:2017-07-16 00:39:21
【问题描述】:

当你执行命令时:

using namespace std;

您可以直接访问 std 命名空间的 所有 元素。但假设您只想使用std::coutstd::endl,那么最好使用指令:

using std::cout;
using std::endl;

所以你只会得到你需要使用的对象,而不是全部。 我的问题是: 有没有办法查看使用命令时添加的内容:

using namespace std;

类似:(我知道这是非常错误的。)

#include <iostream>
using namespace std;

int main(){

cout << std;

return 0;
}

【问题讨论】:

  • 你可以随时查看源代码。
  • C++ 语言规范中没有任何内容可以为您提供此功能。您将需要查看您正在使用的任何 C++ 编译器的文档。也许您的 C++ 编译器有一些特定于编译器的工具,您可以使用它们来获取这些信息。
  • 唯一可用于列出命名空间中内容的真正工具是该命名空间中内容的文档。对于命名空间std,该文档位于标准中(跨越数百页)和可在线获取的各种参考文档集。由于可以跨多个编译单元(和头文件)声明命名空间,因此编译器也可能无法看到命名空间中的所有内容。
  • 一些IDEs 会为您提供命名空间 及其内容的树形视图。如果您打开一个头文件,您可以看到该文件中的所有内容。
  • 您可以简单地在源代码中查找特定类

标签: c++ namespaces std using


【解决方案1】:

查看命名空间提供什么的工具是提供该命名空间的任何内容的文档以及定义命名空间内容的标题。
由于标题通常是高度优化的,而不是真正适合人眼的,所以最好的方法是阅读文档。
例如,std 内部内容的文档可在许多网站上找到。

查看任何其他命名空间,您(希望)也可以获得文档和标题。

对于以编程方式“查看”,恐怕我不得不同意 Sam。

【讨论】:

    【解决方案2】:
    【解决方案3】:

    当您声明您正在使用namespace std 时,您告诉编译器特定命名空间内的所有函数和对象都可以访问,而无需在命名空间名称前加上前缀。

    您导入了iostream,它实际上只是一个标题。但是在这个标头中声明了原型,并且这些原型被组织在命名空间中(在这种情况下为std)。

    根据 C++ 标准开发库,文件iostream 的内容可能会有所不同。但是标准库的实现是……标准的。

    在此处查看源代码示例:GCC - Libstdc++ iostream

    您可以在标题中看到namespace std 中声明的函数:

    00043 namespace std _GLIBCXX_VISIBILITY(default)
    00044 {
    ...
    00061   extern istream cin;       /// Linked to standard input
    00062   extern ostream cout;      /// Linked to standard output
    00063   extern ostream cerr;      /// Linked to standard error (unbuffered)
    00064   extern ostream clog;      /// Linked to standard error (buffered)
    ...
    00067   extern wistream wcin;     /// Linked to standard input
    00068   extern wostream wcout;    /// Linked to standard output
    00069   extern wostream wcerr;    /// Linked to standard error (unbuffered)
    00070   extern wostream wclog;    /// Linked to standard error (buffered)
    ...
    

    请注意,某些 IDE(Visual Studio 和 cons)可能会为您提供语法补全,允许您查看命名空间或类范围内的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      • 2022-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多