一般引用:
#include<iostream>
using namespace std;
class myclass{
int a,b;
public:
myclass(){a=1,b=2;}
void exchange(myclass &x){int temp;temp=x.a;x.a=x.b;x.b=temp;}
void show(){cout<<"a and b is "<<a<<"/t"<<b<<endl;}
};
void exchange(int &x,int &y)
{
int temp;
temp=x;
x=y;
y=temp;
}
int main()
{
myclass cl;
int x,y;
x=10,y=100;
cout<<"before exchange x and y is "<<x<<"/t"<<y<<endl;
exchange(x,y);
cout<<"after exchange x and y is "<<x<<"/t"<<y<<endl;
cl.show();
cl.exchange(cl);
cl.show();
return 0;
}
测试结果:
before exchange x and y is 10 100
after exchange x and y is 100 10
a and b is 1 2
a and b is 2 1
Press any key to continue
独立引用:
测试代码:
#include<iostream>
using namespace std;
int main()
{
int x=1;
int &y=x;
int z=100;
cout<<"x and y is "<<x<<"/t"<<y<<endl;
y=10;
cout<<"x and y is "<<x<<"/t"<<y<<endl;
y=z;
cout<<"x and y is "<<x<<"/t"<<y<<endl;
y++;
cout<<"x and y is "<<x<<"/t"<<y<<endl;
return 0;
}
测试结果:
x and y is 1 1
x and y is 10 10
x and y is 100 100
x and y is 101 101
Press any key to continue