引用

本文通过两个示例展示了C++中引用的基本用法及其如何用于交换变量的值。第一个示例使用了类成员函数进行变量交换,第二个示例则展示了独立变量之间的引用及赋值操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一般引用:

#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

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值