花开自有丶花落 发表于 2016-7-27 19:14:35

对重载函数调用不明确

对重载函数调用不明确,搞不懂
和书上一样却编译不了
#include <iostream>
#include <cstdlib>

using namespace std;
template <typename T>
void swap(T & a, T & b);
int main()
{
    int i=10;
    int j=20;
    cout<<"i,j = "<<i<<", "<<j<<endl;
    cout<<"using compiler generated int swaper:\n";
    swap(i,j);
    cout<<"i,j = "<<i<<", "<<j<<endl;
    double x = 24.5;
    double y = 81.7;
    cout<<"x,y = "<<x<<", "<<y<<endl;
    cout<<"using compiler generated int swaper:\n";
    swap(x,y);
    cout<<"x,y = "<<x<<", "<<y<<endl;
    system("pause");
    return 0;
}
template <typename T>
void swap(T & a, T & b)
{
   T temp;
   temp = a;
   a = b;
   b = temp;
}

littlestar 发表于 2016-7-27 19:14:36

因为用了using namespace std; 内置的swap是在std空间的 所以会有两个swap函数 要么改下函数名 要么去掉using namespace std, 在cout endl前加std::就ok
#include <iostream>
#include <windows.h>


template <typename T>
void swap(T &a, T &b) {
   T temp;
   temp = a;
   a = b;
   b = temp;
}
int main()
{
   
    int i=10;
    int j=20;
    std::cout<<"i,j = "<<i<<", "<<j<<std::endl;
    std::cout<<"using compiler generated int swaper:\n";
    swap(i,j);
    std::cout<<"i,j = "<<i<<", "<<j<<std::endl;
    double x = 24.5;
    double y = 81.7;
    std::cout<<"x,y = "<<x<<", "<<y<<std::endl;
    std::cout<<"using compiler generated int swaper:\n";
    swap(x,y);
    std::cout<<"x,y = "<<x<<", "<<y<<std::endl;
    system("pause");
   
    return 0;
}

花开自有丶花落 发表于 2016-7-27 19:22:29

swap是系统里一个函数,在名称空间std中,重载了swap函数,改掉函数名成功编译
页: [1]
查看完整版本: 对重载函数调用不明确