• C++中参数传递方式


    C++ 中的参数传递方式有2中,pass by value 和 pass by reference,传递数值和传递引用,两者最主要的区别在于
    pass by value: 将数值copy一份给形参,形参数值的改变不影响形参;
    pass by reference : 形式参数能访问参数,形式参数和被穿参数为同一内存地址,形参的改变会引起被传递参数的改变;
    如果不希望改变被传递参数的数值,建议在函数定义的时候函数头中采用 constant 关键字,表示被传递参数数值不会改变。

    pass by value

    int max( int x, int y)
    {
    if(x<=y)
    {
    x = y;
    }
    return x;

    }

    int main(void )
    {
    int x = 7,y =9;
    cout<<"before" << endl;
    cout<< "x value: " << x << " y value: " << y << endl;
    cout<< "max : "<< max(x,y) << endl;
    cout<<"after"<< endl;
    cout<< "x value: " << x << " y value: " << y << endl;
    return 0;

    }

    pass by reference

    一种采用引用的方式调用;另一种采用指针调用。

    引用

    int max( int& x, int& y)
    {
    if(x<=y)
    {
    x = y;
    }
    return x;

    }

    int main(void )
    {
    int x = 7,y =9;
    cout<<"before" << endl;
    cout<< "x value: " << x << " y value: " << y << endl;
    cout<< "max : "<< max(x,y) << endl;
    cout<<"after"<< endl;
    cout<< "x value: " << x << " y value: " << y << endl;
    return 0;

    }

    指针

    int max( int* x, int* y)
    {
    if(x<=y)
    {
    *x = *y;
    }
    return *x;

    }

    int main(void )
    {
    int x = 7,y =9;
    cout<<"before" << endl;
    cout<< "x value: " << x << " y value: " << y << endl;
    cout<< "max : "<< max(&x,&y) << endl;
    cout<<"after"<< endl;
    cout<< "x value: " << x << " y value: " << y << endl;
    return 0;

    }

    小结

    1. 若在调用函数不希望改变被穿参数,采用pass by value 并在 函数定义时添加 constant 修饰符;
    2. pass by reference 有两种参数传递方法,一种通过 引用,另一种是指针;
    3. 若被传递参数数据量比较大,建议采用pass by reference.
  • 相关阅读:
    HPU 1007: 严格递增连续子段(贪心)
    Codeforces Round #224 (Div. 2) A. Ksenia and Pan Scales
    Codeforces Round #224 (Div. 2) A. Ksenia and Pan Scales
    51Nod 1058: N的阶乘的长度(斯特林公式)
    51Nod 1090: 3个数和为0
    CSU 1112: 机器人的指令
    有关刷题时的多组输入问题
    HDU 1060:Leftmost Digit
    《算法导论》— Chapter 6 堆排序
    《算法导论》— Chapter 9 中位数和顺序统计学
  • 原文地址:https://www.cnblogs.com/Finding-bugs/p/14993894.html
Copyright © 2020-2023  润新知