用void 指针实现类似模板的SWAP函数

#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
void swapTest(void *swapA,void *swapB,int size)
{
char *buff=(char *)malloc(size);
memcpy(buff,swapA,size);
memcpy(swapA,swapB,size);
memcpy(swapB,buff,size);
}
int main()
{
double x=0.123;
double y=0.456;
cout<<"x="<<x<<","<<"y="<<y<<endl;
swapTest((void *)&x,(void *)&y,sizeof(double));
cout<<"after swap"<<endl;
cout<<"x="<<x<<","<<"y="<<y<<endl;
cout<<"this is test"<<endl;

}

 

上述变量x,y可以定义为char,int ,float,double

posted on 2015-01-22 10:25  wudymand  阅读(413)  评论(0编辑  收藏  举报

导航