C/C++ 交换两个数,不使用第三个变量, 函数模板来实现

#include <iostream>

template<typename T>
void exchangeTwoNumber(T &t1, T &t2); void test(); int main()
{
int a = , b = ;
double q = 10.1, w = 20.2;
char z = 'z', x = 'x'; std::cout << "交换前的 a = " << a << ", b = " << b << std::endl;
std::cout << "交换前的 q = " << q << ", w = " << w << std::endl;
std::cout << "交换前的 z = " << z << ", x = " << x << std::endl; exchangeTwoNumber(a, b);
exchangeTwoNumber(q, w);
exchangeTwoNumber(z, x);
test(); std::cout << std::endl;
std::cout << std::endl;
std::cout << "交换后的 a = " << a << ", b = " << b << std::endl;
std::cout << "交换后的 q = " << q << ", w = " << w << std::endl;
std::cout << "交换后的 z = " << z << ", z = " << x << std::endl;
} template<typename T>
void exchangeTwoNumber(T &t1, T &t2) //通用的函数模板
{
t1 = t1 + t2;
t2 = t1 - t2;
t1 = t1 - t2;
} void test() //异或的方式,变形成函数模板,编译不通过
{
int a = , b = ;
a ^= b;
b ^= a;
a ^= b; std::cout << "...a=" << a << ", b=" << b << std::endl;
}
上一篇:20140806 交换两个数 extern “C”用法


下一篇:android recovery 升级时间与速度研究