码迷,mamicode.com
首页 > 其他好文 > 详细

值传递和(地址)引用传递

时间:2017-08-18 11:24:15      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:include   基本   blog   out   void   style   span   nbsp   namespace   

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

//值传递:(传值调用)
//效果上:方法内的改变不会影响到方法外
//本质上:只改变了形参的值,并没有改变实参的值
//条件上:形参的类型为基本类型或者一般复杂类型
void swap(int num1,int num2)    //传值调用
{
    int temp;
    temp = num1;
    num1 = num2;
    num2 = temp;
    cout << "swap: " << num1 << " " << num2 << endl;
}

//引用传递:(地址传递)(传址调用)
//效果上:方法内的改变会影响到方法外
//本质上:通过形参指针去改变了实参的值
//条件上:形参为指针和数组和引用时一般都是引用传递,(特殊情况:当函数内只改变了指针的指向,而没有通过指针去修改实参值时,仍然是传值调用)
void swap_point(int *num1,int *num2)    //传址调用
{
    int temp;
    temp = *num1;
    *num1 = *num2;
    *num2 = temp;
    cout << "swap_point:" << *num1 << " " << *num2 << endl;
}

void swap_value(int *num1,int *num2)    //传值调用
{
    int *temp;
    temp = num1;
    num1 = num2;
    num2 = temp;
    cout << "swap_value :" << *num1 << " " << *num2 << endl;
}

void swap_two(int **num1,int **num2)    //传址调用
{
    int *temp = NULL;
    temp = *num1;
    *num1 = *num2;
    *num2 = temp;
    cout << "swap_two: " << **num1 << " " << **num2 << endl;
}

void swap_ref(int &num1,int &num2)      //传址调用
{
    int temp;
    temp = num1;
    num1 = num2;
    num2 = temp;
    cout << "swap_ref " << num1 << " " << num2 << endl;
}

int main()
{
    int a = 10,b = 20;
    cout << "a = " << a << "b = " << b << endl;
#if 0
    swap(a,b);
#endif

#if 0
    swap_point(&a,&b);
#endif

#if 0
    swap_value(&a,&b);
#endif

#if 0
    int *p1 = &a,*p2 = &b;
    cout << *p1 << " " << *p2 << endl;
    swap_two(&p1,&p2);
    cout << "a = " << *p1 << "b = " << *p2 << endl;
#endif

    swap_ref(a,b);
    cout << a << " " << b << endl;
}

 

值传递和(地址)引用传递

标签:include   基本   blog   out   void   style   span   nbsp   namespace   

原文地址:http://www.cnblogs.com/linuxAndMcu/p/7387952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!