c++常量引用

#include <iostream>
using namespace std;
#include <string>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000
#include <string>

//c++引用方式传递
/*void myswap(int *a,int *b)
{
    int temp=*a;
    *a=*b;
    *b=temp;

}*/
/*int myswap(int &a,int &b)//引用c++
{
    int temp=a;
    a=b;
    b=temp;
}*/
/*int &test02()
{
    static int a=10;//局部变量存放在栈区
    return a;

}*/
/*void func(int &ref)
{
    ref=100;
}*/
void show(int &val)
{
    val=1000;
    cout<<val;
}
int main()
{
    /*//引用的基本语法
    int a=10;
    //创建引用
    int &b=a;

    //别名和原名是操作的同一块内存;
    cout<<a<<endl;
    cout<<b<<endl;
    b=100;
    cout<<a<<endl;
    cout<<b<<endl;*/
    //1.引用必须初始化
    //2.引用在初始化后,不可以改变
    /*int a=10;
    int &b=a;
    int c=20;
    b=20;
    cout<<"a="<<a<<endl;
    cout<<"b="<<b<<endl;
    cout<<"c="<<c;*/
    /*int a=10;
    int b=20;
    myswap(a,b);
    cout<<a<<endl;
    cout<<b;*/
    //不能返回局部遍历引用  ,因为第一次可以输出成功,但第二次就不可以了,因为内存已经被释放掉了。
    /*int &ref=test02();//这是别名。
    cout<<"ref="<<ref<<endl;
    cout<<"ref="<<ref<<endl;
    test02()=1000;//如果函数的返回值是引用,

    cout<<"ref="<<ref<<endl;
    cout<<"ref="<<ref<<endl;*/

    /*int a=10;
    int &ref=a;
    ref=20;
    cout<<"a="<<a<<endl;
    cout<<"ref="<<ref;
    //引用的本质就是一个指针常量:*/


    //常量引用,用来修饰形参防止误操作
    //int a=10;
    //int &ref=a;//引用必须引用一块合理的内存空间
    //int const int &ref=10;
    //加上const后,编译器讲代码修改为 int temp=10;const int &ref=temp;
    //加入const只读不改.

    int a=100;
    show(a);
    cout<<a;
    system("pause");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木火火木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值