posts - 24, comments - 11, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

求前辈指点一下,谢谢了.

Posted on 2006-02-28 22:55 quite 阅读(645) 评论(5)  编辑 收藏 引用 所属分类: 求助

//这是个关于函数模板的问题,不明白为什么会出现这样的错误,希望前辈们花二分钟看一下,拜托了啊。 (这是<C++  Pirmer  Plus >第五版
//中的程序,我用的是 Visual C++6.0)


#include<iostream>
using namespace std;

template <class type>
void swap(type &a,type &b)
{
 type temp;
 a=b;
 b=temp;
}

int main()
{
 int i=10;
 int j=20;

 cout<<"i,j="<<i<<","<<j<<endl;
 cout<<"Using compiler_generated int swapper:\n";

 swap(i,j);

 cout<<"Now,i,j="<<i<<","<<j<<endl;

 /*double x=24.5;
 double y=81.7;

 cout<<"x,y="<<x<<","<<y<<endl;
 cout<<"Using compiler_generated double swapper:\n";
 swap(x,y);
 cout<<"Now x,y="<<x<<","<<y<<endl;*/

 return 0;
}

error C2667: 'swap' : none of 2 overload have a best conversion
E:\Documents and Settings\bing\桌面\8.11_funtemp.cpp(14) : error C2668: 'swap' : ambiguous call to overloaded function

Feedback

# re: 求前辈指点一下,谢谢了.  回复  更多评论   

2006-03-09 10:17 by Act.of.War
#include<iostream>
using namespace std;

template <class type>
void swap1(type &a,type &b)
{
type temp;
temp=a;
a=b;
b=temp;
}

int main()
{
int i=10;
int j=20;

cout<<"i,j="<<i<<","<<j<<endl;
cout<<"Using compiler_generated int swapper:\n";

swap1(i,j);

cout<<"Now,i,j="<<i<<","<<j<<endl;

/*double x=24.5;
double y=81.7;

cout<<"x,y="<<x<<","<<y<<endl;
cout<<"Using compiler_generated double swapper:\n";
swap(x,y);
cout<<"Now x,y="<<x<<","<<y<<endl;*/

return 0;
}

# re: 求前辈指点一下,谢谢了.  回复  更多评论   

2006-03-21 11:23 by wutao
template <class type>
void swap(type &a,type &b)
{
type temp=a;
a=b;
b=temp;
}

# re: 求前辈指点一下,谢谢了.  回复  更多评论   

2006-03-28 10:09 by redriver
函数模板要完全的匹配。你写的程序中一个是int,一个是double,所以会出现摸棱两可的情况。编译器是要完全的匹配才行的。

# re: 求前辈指点一下,谢谢了.  回复  更多评论   

2006-04-12 00:08 by sublx
不能用swap这个名字....换一个就可以了。比如Cswap()...

# re: 求前辈指点一下,谢谢了.  回复  更多评论   

2006-10-05 10:22 by 桥风
标准库中有swap()这个函数,所以你不能重名

子函数改个名字

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理