zoukankan      html  css  js  c++  java
  • 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.
  • 相关阅读:
    php date 时间差
    array_merge 和 + 号的的区别
    apache 添加https后导致http无法访问
    php 获取url
    TP5 事务处理
    LeetCode 每日一题 (盛最多水的容器)
    LeetCode 每日一题 (字符串转换整数 (atoi))
    LeetCode 每日一题(5. 最长回文子串)
    LeetCode 每日一题 (3 无重复字符的最长子串)
    LeetCode 每日一题 (两数相加)
  • 原文地址:https://www.cnblogs.com/Finding-bugs/p/14993894.html
Copyright © 2011-2022 走看看