zoukankan      html  css  js  c++  java
  • 按值传递&&按引用传递&&按地址传递

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


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

    #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
    }

  • 相关阅读:
    剑指Offer——对成的二叉树
    剑指Offer——二叉树的下一个节点
    路径总和I、II、III
    性能调优工具
    关于在程序中内存检测的一些知识
    ptmalloc、tcmalloc及 jemalloc总结
    [LeetCode] 43. 字符串相乘
    [LeetCode] 155. Min Stack
    [LeetCode] 380. Insert Delete GetRandom O(1)
    linux内存过高排查
  • 原文地址:https://www.cnblogs.com/shaoguangleo/p/2805843.html
Copyright © 2011-2022 走看看