对重载函数调用不明确
对重载函数调用不明确,搞不懂和书上一样却编译不了
#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;
}
因为用了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;
}
swap是系统里一个函数,在名称空间std中,重载了swap函数,改掉函数名成功编译
页:
[1]