首先,根据书本教材的代码学习,我打出了如下代码:
#include<iostream>
using namespace std;
void swap_i(int *num1,*num2)
{
int t;
t=*num1;
*num1=*num2;
*num2=t;
}
void swap(void *num1,void *num2,int size)
{
char *first=(char*)num1,*second=(char *)num2;
for(int k=0;k<size;k++)
{
char temp;
temp=first[k];
first[k]=second[k];
second[k]=temp;
}
}
int main()
{
int a=3,b=6;
double x=2.3,y=4.5;
char c1[8]="John",c2[8]="Antony";
cout<<"before swap:a="<<a<<"b= "<<b<<endl;
swap_i(&a,&b);
cout<<"after swap:a="<<a<<"b="<<b<<endl;
cout<<"before swap:x="<<x<<"y="<<y<<endl;
swap(&x,&y,sizeof(x));
cout<<"after swap:x="<<x<<"y="<<y<<endl;
cout<<"before swap:c1"<<c1<<"c2="<<c2<<endl;
swap(&c1,&c2,sizeof(c1));
cout<<"after swap:c1="<<c1<<"c2="<<c2<<endl;
return 0;
}
跟书上说的可谓是一毛一样,but……
输出不出来哈哈哈哈
成功喜获一个错误:
在我的网络搜索查询无果的情况下
我看着错误行显示的error
突然
悟了……
想要在之前得到一个身份
但是我第一个形参括号内的第二个没有命名
因此:
只需在num2前面加个int
就可以解决问题啦
using namespace std;
void swap_i(int *num1,int *num2)
{
int t;
t=*num1;
*num1=*num2;
*num2=t;
}
void swap(void *num1,void *num2,int size)
{
char *first=(char*)num1,*second=(char *)num2;
for(int k=0;k<size;k++)
{
char temp;
temp=first[k];
first[k]=second[k];
second[k]=temp;
}
}
int main()
{
int a=3,b=6;
double x=2.3,y=4.5;
char c1[8]="John",c2[8]="Antony";
cout<<"before swap:a="<<a<<"b= "<<b<<endl;
swap_i(&a,&b);
cout<<"after swap:a="<<a<<"b="<<b<<endl;
cout<<"before swap:x="<<x<<"y="<<y<<endl;
swap(&x,&y,sizeof(x));
cout<<"after swap:x="<<x<<"y="<<y<<endl;
cout<<"before swap:c1"<<c1<<"c2="<<c2<<endl;
swap(&c1,&c2,sizeof(c1));
cout<<"after swap:c1="<<c1<<"c2="<<c2<<endl;
return 0;
}
void swap_i(int *num1,int *num2)
最后成功输出交换前后的数: