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

关于swap的函数模版,该如何解决

2012-05-24 
关于swap的函数模版#includeiostreamusing namespace stdtemplatetypename Tvoid swap(T *a,T *b){T

关于swap的函数模版
#include<iostream>
using namespace std;

template<typename T>
void swap(T *a,T *b)
{
T *t;*t=*a;*a=*b;*b=*t;
}

void main()
{
int c=3,d=4;
swap(c,d);
cout<<c<<","<<d<<endl;
}

上面这个可以运行

#include<iostream>
using namespace std;

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

void main()
{
int c=3,d=4;
swap(c,d);
cout<<c<<","<<d<<endl;
}

上面这个不能运行

为什么指针可以运行,引用不能运行?是因为系统函数的swap中是用引用么?

[解决办法]
不是你函数本身的问题,而是std中包含了如下的函数,与你定义的恰好相同。
所以指针可以,引用不行了

C/C++ code
template<class _Ty> inline    void swap(_Ty& _Left, _Ty& _Right)    {    // exchange values stored at _Left and _Right    if (&_Left != &_Right)        {    // different, worth swapping        _Ty _Tmp = _Left;        _Left = _Right;        _Right = _Tmp;        }    }
[解决办法]
第一个也是错的。
T *t;*t=*a;*a=*b;*b=*t;

t都没申请空间,就直接解引用赋值了
改成T t; t=*a;*a=*b;*b=t;

热点排行