当前位置:编程学习 > C/C++ >>

这道C++程序哪错了?

#include <iostream>
template <class any>
void swap(any &a,any &b);
int main()
{
using namespace std;
int i=10;
int j=20;
cout<<"i,j = "<<i<<","<<j<<".\n";
cout<<"using compiler-generated int swapper: \n";
swap(i,j);
cout<<"now i,j = "<<i<<","<<j<<".\n";
double x=24.5;
double y=81.7;
cout<<"x,y = "<<x<<","<<y<<".\n";
cout<<"using compiler-generated int swapper: \n";
swap(x,y);
cout<<"now x,y = "<<x<<","<<y<<".\n";
return 0;
}
template <class any>
void swap(any &a,any &b)
{
any temp;
temp=a;
a=b;
b=temp;
}
答案:
因为你定义的这个模板函数跟C++标准库中的swap函数名字一样,所以编译器不知道要调用哪个。最简单的方法是把函数名改一下就好。

#include <iostream>
template <class any>
void Swap(any &a, any &b);
int main()
{
using namespace std;
int i = 10;
int j = 20;
cout << "i,j = " << i << "," << j << ".\n";
cout << "using compiler-generated int swapper: \n";
Swap(i, j);
cout << "now i,j = " << i << "," << j << ".\n";
double x = 24.5;
double y = 81.7;
cout << "x,y = " << x << "," << y << ".\n";
cout << "using compiler-generated int swapper: \n";
Swap(x, y);
cout << "now x,y = " << x << "," << y << ".\n";
return 0;
}
template <class any>
void Swap(any &a, any &b)
{
any temp;
temp = a;
a = b;
b = temp;
}

或者不要用using namespace std;这条语句,在用到cout的时候用std::cout代替。

#include <iostream>
template <class any>
void swap(any &a, any &b);
int main()
{
//using namespace std;
int i = 10;
int j = 20;
std::cout << "i,j = " << i << "," << j << ".\n";
std::cout << "using compiler-generated int swapper: \n";
swap(i, j);
std::cout << "now i,j = " << i << "," << j << ".\n";
double x = 24.5;
double y = 81.7;
std::cout << "x,y = " << x << "," << y << ".\n";
std::cout << "using compiler-generated int swapper: \n";
swap(x, y);
std::cout << "now x,y = " << x << "," << y << ".\n";
return 0;
}
template <class any>
void swap(any &a, any &b)
{
any temp;
temp = a;
a = b;
b = temp;
}
我稍微改了一下 可以用了 你看看是不是你要的
#include <iostream.h>
template <class any>
void swap(any &a,any &b);
int main()
{

int i=10;
int j=20;
cout<<"i,j = "<<i<<","<<j<<".\n";
cout<<"using compiler-generated int swapper: \n";
swap(i,j);
cout<<"now i,j = "<<i<<","<<j<<".\n";
double x=24.5;
double y=81.7;
cout<<"x,y = "<<x<<","<<y<<".\n";
cout<<"using compiler-generated int swapper: \n";
swap(x,y);
cout<<"now x,y = "<<x<<","<<y<<".\n";
return 0;
}
template <class any>
void swap(any &a,any &b)
{
any temp;
temp=a;
a=b;
b=temp;
}
首先问下你是C还是C++?

上一个:C++编程问题。达人指点下
下一个:JAVA C++ 选哪个好啊?

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,