C++引用

值传递:

        形参不会修饰实参

#include<iostream>
using namespace std;
void Swap(int a ,int b)

{
    int temp=0;
    temp=a;
    a=b;
    b=temp;

}

int main()
{
int a=10;
int b=20;
Swap(a,b);
std::cout<<a<<emdl;
std::cout<<b<<endl;
}

输出结果为:

10

20

地址传递:

        形参修饰实参

#include<iostream>
using namespace std;
void Swap(int* a, int* b)

{
    int temp = 0;
    temp = *a;
    *a = *b;
    *b = temp;
}

int main()
{
    int a = 10;
    int b = 20;
    Swap(&a, &b);
    std::cout << a << std::endl;
    std::cout << b << std::endl;
}

输出为:

20

10

引用传递:

        形参修饰实参

#include<iostream>
using namespace std;
void Swap(int& a, int& b)

{
    int temp = 0;
    temp = a;
    a = b;
    b = temp;

}

int main()
{
    int a = 10;
    int b = 20;
    Swap(a, b);
    std::cout << a << endl;
    std::cout << b << endl;
}

输出为 :

20 

10

常量引用

      使用场景:  修饰形参,防止误操作

引用必须引用一段合法内存空间,不能直接赋值

若写为:int & a=10        错误!        int b=10; int&a=b;

可以写为 :const int &a=10;        或者: int temp=10; const int&a=temp;

加入const修饰后,该值不可被修改        如: const int &a=10;  a=20;        错误!

使用场景:

#include<iostream>
using namespace std;

void printValue(int &a )

{
    
    cout<<"a="<<a<<endl;;
    a=1000;
}

int main()
{
    int a=10;
    printValue(a);
    cout<<"a="<<a<<endl;

}

        第二次输出的a=1000;

为防止输入参数(实参)被修改

#include<iostream>
using namespace std;

void printValue(const int &a )

{
    
    cout<<"a="<<a<<endl;;
    
}

int main()
{
    int a=10;
    printValue(a);
    cout<<"a="<<a<<endl;

}

函数体中不允许修改形参,从而不会改变实参数值。

相比于 值传递 常量修饰的引用 不需要创建额外内存空间进行赋值

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值