码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-01-22 11:03:51      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

#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

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

标签:

原文地址:http://www.cnblogs.com/wudymand/p/4240951.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!