C++ 引用返回 C++函数(二)

还记得引用传递吗?当时我们为了与按值传参区分,我们把它叫做按址传参。而今天我们将与引用返回区分。

按值传参和按址传参可以参考博客C++函数(二)的最后一部分。

引用返回其实和引用传递一样。引用传递使得传入的变量和所对应参数的地址相同,而引用返回使得返回值的地址与传给的变量的地址相同。

我们先来看下面的代码

#include <iostream>

using namespace std;

//加法,按值传参
int add(int a, int b){
    int c;
    cout << "add函数中a的地址是:" << &a << endl;
    cout << "add函数中b的地址是:" << &b << endl;
    c = a + b;
    cout << "add函数中c的地址是:" << &c << endl;
    return c;
}

//减法,按址传参,即引用传递
int sub(int& a, int& b){
    int c;
    cout << "sub函数中a的地址是:" << &a << endl;
    cout << "sub函数中b的地址是:" << &b << endl;
    c = a - b;
    cout << "sub函数中c的地址是:" << &c << endl;
    return c;
}

//除法,引用返回(与引用传递相对)
int& division(int a, int b){
    int c;
    cout << "division函数中a的地址是:" << &a << endl;
    cout << "division函数中b的地址是:" << &b << endl;
    c = a / b;
    cout << "division函数中c的地址是:" << &c << endl;
    return c;
}

int main()
{
    int a = 1, b = 2, c;
    cout << "a的地址是:" << &a << endl;
    cout << "b的地址是:" << &b << endl;
    cout << "---------------------------" << endl;


    c = add(a, b);
    cout << "add函数返回值是:" << c << endl;
    cout << "---------------------------" << endl;

    c = sub(a, b);
    cout << "sub函数返回值是:" << c << endl;
    cout << "---------------------------" << endl;

    c = division(a, b);
    cout << "division函数返回值是:" << c << endl;

    return 0;
}

运行结果:

 我们可以看到,add函数和sub函数都可以最终都可以有返回值,但是到division这个函数的时候,程序执行了一段时间(从执行时间可以看出来较久),没有执行最后一句话,并且以一个负数返回,说明程序发生了错误。

这是因为变量c接受了division的返回值时,其地址与division函数中的局部变量c的地址是一样的,而division函数中的局部变量c的生命周期与division函数的生命周期相同,故在函数执行完之后就会销毁。

因为这个值已经被销毁了,所以下一句自然访问不到,也就没有办法执行了。

猜你喜欢

转载自www.cnblogs.com/bwjblogs/p/12968829.html