Swap函数老是出问题,说明理解的不透彻

现swap( x, y )交换数据x与y的值.
程序一:利用引用来实现.
在VC6.0可以通过,运行也正确.

程序一:
#include

template
void swap( T &x, T &y ) 

T temp; 

temp = x;
x = y;
y = temp;
}

int main()
{
double a, b;
a = 7.7;
b = 8.8;
cout<<"before swap, double a:"<
swap( a, b );
cout<<"after swap, double a:"<

long a1, b1;
a1 = 7;
b1 = 8;
cout<<"before swap, long a1:"<
swap( a1, b1 );
cout<<"after swap, long a1:"<

return 0;
}

程序二:利用指针来实现.
在VC6.0可以通过,运行也正确.

程序二:
#include

template

void swap( T *x, T *y ) 

T temp; 

temp = *x;
*x = *y;
*y = temp;
}

int main()
{
double a, b;
a = 7.7;
b = 8.8;
cout<<"before swap, double a:"<
swap( &a, &b );
cout<<"after swap, double a:"<

long a1, b1;
a1 = 7;
b1 = 8;
cout<<"before swap, long a1:"<
swap( &a1, &b1 );
cout<<"after swap, long a1:"<

return 0;
}

你可能感兴趣的:(Swap函数老是出问题,说明理解的不透彻)