代码逻辑和c语言没有什么区别,
#include <iostream>
using namespace std;
template<typename T>
T MAX(T *a, T *b){
T temp;
temp = *a;
*a = *b;
*b = temp;
}
int main(){
int a = 2,b = 3;
cout << "a = "<<a<<"b = "<< b<<endl;
MAX<int>(&a,&b);
cout << "a = "<<a<<"b = "<< b<<endl;
double x = 1.2,y = 23.3;
cout << "x = "<<x<<"y = "<< y<<endl;
MAX<double>(&x,&y);
cout << "x = "<<x<<"y = "<< y<<endl;
return 0;
}
执行结果:
但是注意:
在交换函数中,中间量不要定义为指针,不然会报错(核心已转储);
不知道什么原因,有知道的评论区告诉一声。谢谢!!!!