13-【每天亿点点C++,简单又有趣儿】引用

引用 给变量起别名

语法:数据类型 &别名 = 原名

#include<iostream>
#include<string>
using namespace std;

void swap_01(int a,int b);
void swap_02(int * a,int * b);
void swap_03(int &a,int &b);
int& test_01();
int& test_02();
void showValue(const int & val);


int main()
{
    /*创建引用*/
    int a = 10;
    int &b = a;//创建引用
    cout << "a = " <<a << endl;
    cout << "b = " <<b << endl;
    b = 100;
    cout << "a = " <<a << endl;
    cout << "b = " <<b << endl;


    /*引用的注意事项*/
    // 1-引用必须要初始化
    //  例如:  int &b;
    // 2-引用一旦初始化就不可以更改
    //  例如:  int &b = c;  //已经是a的别名了,不能再是c的了
    int d = 44;
    b = d; //赋值操作
    cout << "a = " <<a << endl;
    cout << "b = " <<b << endl;

    /*引用做函数参数*/
    int c = 66;

    swap_01(a,c);//值传递
    cout << "a = " <<a << endl;
    cout << "c = " <<c << endl;


    swap_02(&a,&c);//地址传递
    cout << "a = " <<a << endl;
    cout << "c = " <<c << endl;

    swap_03(a,c);//引用传递
    cout << "a = " <<a << endl;
    cout << "c = " <<c << endl;

    /*引用做函数返回值*/
    // 1、不要返回局部变量的引用 非法操作
    // int &ref = test_01();
    // cout << ref << endl;
    // 2、函数的调用可以做左值
    int &ref2 = test_02(); //a是原名 ref2是别名
    cout << ref2 << endl;
    test_02() = 100000;
    cout << ref2 << endl;


    /*引用的本质*/
    //就是指针常量.指针是常量

    // 等价
    // int &b = a;
    // int * const b = &a;

    // 等价
    // b = 20;
    // *b = 20;

    // 等价
    // void func(int& ref)
    // int * const ref ;

    /*常量引用*/
    // 场景一    const 修饰 防止误操作
    const int & ref4 = 10;  //没有原名,只有别名
    // 不可修改 ref4 = 40;

    // 场景一   修饰形参防止误操作
    showValue(ref4);


}
void swap_01(int a,int b)
{
    int tmp = a;
    a = b;
    b = tmp;
}

void swap_02(int * a,int * b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

void swap_03(int &a,int &b)//形参是别名
{
    int tmp = a;
    a = b;
    b = tmp;
}

int& test_01()
{
    int a = 10;
    return a;
}
int& test_02()
{
    static int a = 1110; //静态变量,存放在全局区
    return a;
}

void showValue(const int & val)
{
    // val = 1000 误操作
    cout << "val = " << val << endl;
}

输出
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/magic_shuang/article/details/107549900
今日推荐