2017C++基础——网课笔记(10到14)

十. 引用的本质

1. 引用所占用的大小,跟指针是相等的。

2. 常量需要初始化,引用也要初始化,引用可能本质上是一常量


const int a =10;

int& a=b;

十一.常量指针
对于 int array[10]。。array是位于“常量区”的。


而int & r=a; 而言,r也是位于常量区,它的*r指向a
十二.引用作为函数的返回值
#include <iostream>

using namespace std;

//引用作为返回值,不要返回局部变量的引用。
int& getFunc()
{
    int a = 10;
    return a;
} //int &temp = a;

//引用作为返回值,返回静态变量是ok的,因为在整个程序范围内都是有效的。
//或者malloc的这种动态内存分配也是可以的。
int& getFunc1()
{
    static int a = 10;

    return a;
}



int main()
{
    int main_a = 0;

    main_a = getFunc(); //main_a = temp; 而这里temp是a的别名
                        //也因此,上一行是一个数值拷贝的动作
    cout<<"main_a = "<<main_a<<endl;

    cout<<"-------------"<<endl;

    int &main_a_re = getFunc();

    cout<<"main_a_re = "<<main_a_re<<endl;

    cout<<"main_a_re = "<<main_a_re<<endl;

    cout<<"----------------"<<endl;

    //引用如果当函数返回值的话,函数可以当左值,
    //这是因为这个时候相当于对变量的别名了
    getFunc1() = 1000;
    cout<< "a= "<<getFunc1()<<endl;

    return 0;
}

/*
运行结果:
main_a = 10
-------------
main_a_re = 10    //这里是10的原因是还没有压栈,这也是我们为什么需要输出两次这个值的原因
main_a_re = 4199040

*/


这里需要注意一点,当我们把引用作为一个返回值时,这个返回值绝对不能是局部变量,否则返回值将会是未知,且错误的

十三.指针引用
#include <iostream>
#include <string.h>
#include <stdlib.h >

using namespace std;

struct teacher
{
    int id;
    char name[64];
};
//这是传统的C语言的方法
int get_mem(struct teacher ** tpp)
{
    struct teacher * tp = NULL;
    tp = (struct teacher*) malloc(sizeof(struct teacher));
    if(tp == NULL)
    {
        return -1;

    }

    tp->id = 100;
    strcpy(tp->name, "li4");

    *tpp = tp;

    return 0;
}

//这是传统的C语言的方法
void free_teacher(struct teacher **tpp)
{
    if(tpp == NULL)
    {
        return;
    }

    struct teacher *tp =  *tpp;
    if(tp != NULL)
    {
        free(tp);
        *tpp = NULL;
    }
}

//这是加入引用后的情况
int get_mem2(struct teacher* &tp)
{
    tp=(struct teacher*)malloc(sizeof(struct teacher));
    if(tp == NULL){
        return -1;
    }
    tp->id=300;
    strcpy(tp->name,"wang5");

    return 0;
}

//这是加入引用后的情况
void free_teacher2(struct teacher * &tp)
{
    if(tp != NULL)
    {
        free(tp);
        tp = NULL;
    }
}

int main()
{
    struct teacher* tp = NULL;

    get_mem(&tp);
    cout<<"id = "<<tp->id<<", name = "<<tp->name<<endl;
    free_teacher(&tp);

    cout<<"---------------------"<<endl;

    get_mem2(tp);
    cout<<"id = "<<tp->id<<", name = "<<tp->name<<endl;
    free_teacher2(tp);

    return 0;
}

/*
程序输出结果:

id = 100, name = li4
---------------------
id = 300, name = wang5

*/


 


十四.const引用(略)


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值