• 按值传递&&按引用传递&&按地址传递


    按值传递:不改变外部对象


    按引用传递&&按地址传递:允许改变外部对象

    #include <iostream>
    #include <cstdlib>
    #include <string>
    using namespace std;

    //passing by refedrence
    void f(int &r)
    {
        cout << "r = " << r << endl;
        cout << "&r = " << &r << endl;
        r = 5 ;
        cout << "r = " << r << endl;
    }

    //passing by value
    void f(int a)
    {
        cout<<"a= "<<a<<endl;
        a = 5;
        cout << "a= " << a <<endl;
    }

    //passing by address
    void f(int *p)
    {
        cout << "p = " << p << endl;
        cout << "*p = " << *p << endl;
        *p = 5;
        cout << "p = " << p << endl;
    }

    int main()
    {
    //passing by reference
    int x = 47 ;
    cout << "x = " << x <<endl;
    cout << "&x = " << &x << endl;
    f(x);//Looks like pass-by-value
          //is actually pass by reference
    cout << "x = " << x << endl;
    //output
    x = 47
    &x = 0x7FFF1D5C9B4C
    r = 47
    &r = 0x7FFF1D5C9B4C
    r = 5
    x = 5

    //passing by address
    int x = 47;
    cout << "x = " << x << endl;
    cout << "&x = " << &x << endl;
    f(&x);
    cout << "x = " << x << endl;
    //output
    ////////////////////////////////
    x = 47
    &x = 0x7FFF9746423c
    p = 0x7FFF9746423c
    *p = 47
    p = 0x7FFF9746423c
    x = 5


    //passing by value
    int x = 97 ;
    cout << "x=" << x <<endl;
    f(x);
    cout << "x=" << x <<endl;
    //output
    ///////////////////////////////
    x = 47
    a = 47
    a = 5
    x = 47
    }

  • 相关阅读:
    《算法导论》读书笔记
    【原创】POI操作Excel导入导出工具类ExcelUtil
    10-JMM
    09-字节码执行引擎
    08-类加载机制
    07-前端编译与优化(待补充)
    06-字节码指令
    05-类文件结构
    04-垃圾回收(2)
    03-垃圾回收(1)
  • 原文地址:https://www.cnblogs.com/shaoguangleo/p/2805843.html
Copyright © 2020-2023  润新知