c++引用返回 和 引用与指针


一、

#include<iostream>
#include<assert.h>
using namespace std;
//引用返回
// 1、减少拷贝
// 调用者可以修改返回对象
//int& count()
//{
//    static int n = 0;
//    n++;
//    return n;
//}
//#define N 10
//typedef struct Array
//{
//    int a[N];
//    int size;
//}AY;
//int& postat(AY& ay, int i)
//{
//    assert(i < N);
//    return ay.a[i];
//}
//int main()
//{
//    //int ret = count();
//    AY ay;
//    for (int i = 0; i < N;++i)
//    {
//        postat(ay, i) = i * 10;
//    }
//    for (int i = 0; i < N; ++i) {
//        cout << postat(ay, i) << " ";
//    }
//    cout << endl;
//    return 0;
//}
//
int& add(int a, int b)
{
    int c = a + b;
    return c;
}
int main()
{
    int& ret = add(1, 2);
    //add(3, 4);
    cout << "add(1,2) is :" << ret << endl;
    cout << "add(1,2) is :" << ret << endl;
    return 0;
}

结论:如果函数返回时,出了函数作用域,如果返回对象(静态、全局、上一层栈帧、malloc的等等)还在(还没给系统),则可以使用引用返回,如果已经还给系统了,则必须使用传参返回。  如果使用引用返回,结果是未定义。

二、

//指针和引用,赋值/初始化 权限可以缩小,保持,但不能放大

//权限放大
/*const int c = 2;
int& d = c;

const int* p1 = NULL;
int* p2 = p1;*/
//例子
const int m = 1;
int n = m;

//权限保持
const int c = 2;
const int& d = c;

const int* p1 = NULL;
const int* p2 = p1;

//权限缩小
int x = 1;
const int& p4 = p3;

int* p3 = NULL;
const int* p4 = p3;

int conut()
{
    int n = 0;
    n++;
    return n;
}
int main()
{
    int ret = conut();//拷贝
    int& ret = conut();//出错
    const int& ret = conut();//因为返回不是n,而是临时变量不可修改,
    


    int i = 10;
    cout << (double)i << endl;//隐式转换
    double dd = i;//显式转换,先产生临时变量(double类型),再给dd
    double& rd = i;//临时变量具有常性,故出错
    const double& rd = i;

    return 0;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值