首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

!看看这个程序错在哪!

2012-07-31 
求助!!!看看这个程序错在哪!!!#includeiostreamusing namespace stdtemplatetypename Tvoid swap(T&

求助!!!看看这个程序错在哪!!!
#include<iostream>

using namespace std;

template<typename T>
void swap(T& a, T& b)
{
  T temp = a;
  a = b;
  b = temp;


int main()
{
  double dx = 3.5, dy = 5.6;
  int ix = 6, iy = 7, ia = 303, ib = 505;
  string s1 = "good", s2 = "better";
  cout<<"double dx="<<dx<<", dy="<<dy<<"\n";
  cout<<"int ix="<<ix<<", iy="<<iy<<"\n";
  cout<<"string s1=\""<<s1<<"\", s2=\""<<s2<<"\"\n";
  swap(dx, dy);
  swap(ix, iy);
  swap(s1, s2);
  swap(ia, ib);
  cout<<"\nafter swap:\n";
  cout<<"double dx="<<dx<<", dy="<<dy<<"\n";
  cout<<"int ix="<<ix<<", iy="<<iy<<"\n";
  cout<<"string s1=\""<<s1<<"\", s2=\""<<s2<<"\"\n";
  system("PAUSE");
}


[解决办法]
看下面的代码和注释就明白了。

C/C++ code
#include <iostream>#include <string>            // 增加这行using namespace std;template<typename T>void Swap(T& a, T& b)        // 已经有库函数叫swap,所以要改名{  T temp = a;  a = b;  b = temp;} int main(){  double dx = 3.5, dy = 5.6;  int ix = 6, iy = 7, ia = 303, ib = 505;  string s1 = "good", s2 = "better";  cout<<"double dx="<<dx<<", dy="<<dy<<"\n";  cout<<"int ix="<<ix<<", iy="<<iy<<"\n";  cout<<"string s1=\""<<s1<<"\", s2=\""<<s2<<"\"\n";  Swap<double>(dx, dy);        // 调用的时候,最好加上模板参数,下面几句类似。  Swap<int>(ix, iy);  Swap<string>(s1, s2);  Swap<int>(ia, ib);  cout<<"\nafter swap:\n";  cout<<"double dx="<<dx<<", dy="<<dy<<"\n";  cout<<"int ix="<<ix<<", iy="<<iy<<"\n";  cout<<"string s1=\""<<s1<<"\", s2=\""<<s2<<"\"\n";  system("PAUSE");} 

热点排行