【问题标题】:swap fails in case of int and works in case of string交换在 int 的情况下失败,在 string 的情况下有效
【发布时间】:2011-06-01 16:35:23
【问题描述】:
#include <iostream>
#include <string>
#include <algorithm>    
int main()
{
 std::string str1 = "good", str2 = "luck";
 swap(str1,str2); /*Line A*/
 int x = 5, y= 3;
 swap(x,y); /*Line B*/
}

如果我评论 B 行代码编译 (http://www.ideone.com/hbHwf) 而评论 A 行代码无法编译 (http://www.ideone.com/odHka) 我得到以下错误:

error: ‘swap’ was not declared in this scope

为什么我在第一种情况下没有收到任何错误?

【问题讨论】:

    标签: c++ swap


    【解决方案1】:

    swap(str1, str2) 工作是因为Argument dependent lookup

    PS:Pitfalls of ADL

    【讨论】:

      【解决方案2】:

      您不符合条件swap;由于ADL,它在传递std::string 对象时有效,但由于int 不在命名空间std 中,您必须完全限定调用:

      std::swap(x, y);
      

      或使用 using 声明:

      using std::swap;
      swap(x, y);
      

      【讨论】:

        【解决方案3】:

        字符串位于 std:: 命名空间中,因此编译器会在那里查找 swap() 字符串。整数不是,所以它没有。你想要:

        std::swap(x,y);
        

        【讨论】:

          【解决方案4】:

          在这两种情况下,您都应该使用std::swap() 而不是swap()

          【讨论】:

            猜你喜欢
            • 2016-01-07
            • 1970-01-01
            • 1970-01-01
            • 2016-09-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-08-09
            相关资源
            最近更新 更多