鱼C论坛

 找回密码
 立即注册
查看: 1746|回复: 2

对重载函数调用不明确

[复制链接]
发表于 2016-7-27 19:14:35 | 显示全部楼层 |阅读模式
10鱼币
对重载函数调用不明确,搞不懂
和书上一样却编译不了
  1. #include <iostream>
  2. #include <cstdlib>

  3. using namespace std;
  4. template <typename T>
  5. void swap(T & a, T & b);
  6. int main()
  7. {
  8.     int i=10;
  9.     int j=20;
  10.     cout<<"i,j = "<<i<<", "<<j<<endl;
  11.     cout<<"using compiler generated int swaper:\n";
  12.     swap(i,j);
  13.     cout<<"i,j = "<<i<<", "<<j<<endl;
  14.     double x = 24.5;
  15.     double y = 81.7;
  16.     cout<<"x,y = "<<x<<", "<<y<<endl;
  17.     cout<<"using compiler generated int swaper:\n";
  18.     swap(x,y);
  19.     cout<<"x,y = "<<x<<", "<<y<<endl;
  20.     system("pause");
  21.     return 0;
  22. }
  23. template <typename T>
  24. void swap(T & a, T & b)
  25. {
  26.      T temp;
  27.      temp = a;
  28.      a = b;
  29.      b = temp;
  30. }
复制代码

最佳答案

查看完整内容

因为用了using namespace std; 内置的swap是在std空间的 所以会有两个swap函数 要么改下函数名 要么去掉using namespace std, 在cout endl前加std::就ok
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-7-27 19:14:36 | 显示全部楼层
因为用了using namespace std; 内置的swap是在std空间的 所以会有两个swap函数 要么改下函数名 要么去掉using namespace std, 在cout endl前加std::就ok
  1. #include <iostream>
  2. #include <windows.h>


  3. template <typename T>
  4. void swap(T &a, T &b) {
  5.      T temp;
  6.      temp = a;
  7.      a = b;
  8.      b = temp;
  9. }
  10. int main()
  11. {
  12.    
  13.     int i=10;
  14.     int j=20;
  15.     std::cout<<"i,j = "<<i<<", "<<j<<std::endl;
  16.     std::cout<<"using compiler generated int swaper:\n";
  17.     swap(i,j);
  18.     std::cout<<"i,j = "<<i<<", "<<j<<std::endl;
  19.     double x = 24.5;
  20.     double y = 81.7;
  21.     std::cout<<"x,y = "<<x<<", "<<y<<std::endl;
  22.     std::cout<<"using compiler generated int swaper:\n";
  23.     swap(x,y);
  24.     std::cout<<"x,y = "<<x<<", "<<y<<std::endl;
  25.     system("pause");
  26.    
  27.     return 0;
  28. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-7-27 19:22:29 | 显示全部楼层
swap是系统里一个函数,在名称空间std中,重载了swap函数,改掉函数名成功编译
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-14 15:55

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表