3 引用的使用

1 引用作为函数形参

#include <cstdlib>
#include <iostream>

using namespace std;

struct teacher{
       int id;
       char name[64];
};

int getmem_1(teacher** t)
{
    teacher* temp = NULL;
    
    temp = (teacher*)malloc(sizeof(teacher));
    if(temp == NULL)
            return -1;
            
    temp->id = 100;
    strcpy(temp->name, "abc");
    
    *t = temp;
    
    return 0;
}

int freemem_1(teacher** t)
{
    teacher* temp = *t;
    
    if(temp == NULL)
            return -1;
    
    free(temp);
    *t = NULL;
    
    return 0;
}

int getmem_2(teacher* & t)
{
    t = (teacher*)malloc(sizeof(teacher));
    if(t == NULL)
            return -1;
            
    t->id = 100;
    strcpy(t->name, "abc");
    
    return 0;
}

int freemem_2(teacher* & t)
{
    if(t == NULL)
         return -1;
         
    free(t);
    t = NULL;
    
    return 0;
}

int main(int argc, char *argv[])
{
    teacher* t = NULL;
    
    getmem_1(&t);
    cout << "name: " << t->name << " id: " << t->id << endl;
    freemem_1(&t);
    
    getmem_2(t);
    cout << "name: " << t->name << " id: " << t->id << endl;
    freemem_2(t);
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

比较指针与引用的区别,引用的使用明显要比指针使用方法简单一些,不容易出错。

2 引用作为函数返回值

#include <cstdlib>
#include <iostream>

using namespace std;

struct teacher{
       int id;
       char name[64];
};

teacher g_t = {
     100,
     "abc"   
};

teacher& get_id(void)
{ 
        return g_t;  
}

int main(int argc, char *argv[])
{
    cout << g_t.id << endl;
    
    get_id().id = 20;
    cout << g_t.id << endl;
    
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

引用作为函数的返回值,需要注意的是不能将局部变量作为引用返回;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值