【问题标题】:In what functions do I got to use std::?我必须在哪些功能中使用 std::?
【发布时间】:2021-02-04 02:09:46
【问题描述】:

这是我的第一篇文章,我是初学者。我正在学习。

我读到使用using namespace std 被认为是一种不好的做法,我有点理解为什么,所以我每次都尝试使用std::。 我知道我必须在cout 和cin 中使用它。

我的问题是,我还可以在哪些其他功能中使用 std::?我在哪里可以看到列表或类似的东西?

谢谢。

【问题讨论】:

  • C++ 标准中的所有内容都以std 开头。 Pretty big list。从 C 中采用的东西可能有点不同。例如,std::pow 与 pow 不完全相同。
  • eel.is/c++draft 跟踪(据我所知)最新版本的草稿。您必须稍作改动才能找到最接近您正在编译的已发布标准的修订版。 Stack Overflow 上有一个映射列表,但我现在找不到。
  • cppreference.com 是探索 STL 和获取最新在线文档的好地方。从一开始就使用标准是好的。玩得开心!

标签: c++ std


【解决方案1】:

名单真的很大。但是如果您在需要时不使用它,编译器会警告您。如果您使用体面的 IDE,它会有所帮助。有一堆可以免费使用,所以只需挑选一个即可。

几乎所有你可能调用的东西都需要某种命名空间前缀,其中 std:: 是最常见的。

请注意,如果您执行以下操作,那并没有那么糟糕:

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

cout << "This is a string" << endl;

但如果你这样做:

using namespace std;

然后,您基本上是在拉入所有 std -- 这增加了发生名称冲突的可能性。

【讨论】:

    【解决方案2】:

    在https://repl.it/@JomaCorpFX/NameCollision#main.cpp 上检查/测试此代码

    #include <iostream>
    
    namespace std{
      static int Add(int a, int b)
      {
        return a + b;
      }
    }
    
    namespace math{
      static int Add(int a, int b)
      {
        return a + b;
      }
    }
    
    static int Add(int a, int b)
    {
      return a + b;
    }
    
    using namespace std;
    using namespace math;
    
    int main() {
      std::cout << std::Add(1,2) << std::endl; //OK
      std::cout << math::Add(1,2) << std::endl; //OK
      std::cout << ::Add(1,2) << std::endl; //OK
      std::cout << Add(1,2) << std::endl;//ERROR. Ambiguous call to "std::Add" or "math::Add" or local function "Add" // Comment this line for fix the error or complete the correct namespace or delete using namespace statements.
    }
    

    编译时输出

    main.cpp:29:16: error: call to 'Add' is ambiguous
      std::cout << Add(1,2) << std::endl;//ERROR. Ambiguous call to "std::Ad...
                   ^~~
    main.cpp:4:14: note: candidate function
      static int Add(int a, int b)
                 ^
    main.cpp:11:14: note: candidate function
      static int Add(int a, int b)
                 ^
    main.cpp:17:12: note: candidate function
    static int Add(int a, int b)
               ^
    1 error generated.
    compiler exit status 1
    

    如果您键入“using namespace std”语句,您可能会导致函数名称/签名冲突,另一个标头可以包含相同的函数签名而没有命名空间。

    如果您包含一个新标头,该标头可以包含 1 个或 n 个函数,这些函数会使用您的代码对签名进行数学运算,那么您的原始代码可能会中断。编译器显示代码错误,很头疼。

    最佳做法是使用完整名称,以避免这种情况。花更多的时间,获得更多的可读性并减少错误。

    std::Add
    math::Add
    ::Add
    
    std::cout
    std::string
    

    为了约定,只有 C++ 标准库可以有命名空间 std。

    【讨论】:

    • 标准禁止将自己的函数添加到std。如果你这样做了,你的程序的行为是不确定的。
    猜你喜欢
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    相关资源
    最近更新 更多