• C++ 值类型和引用类型传递示例


    // win32test.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    
    
    void swap_point(int * &a , int * &b){
    	int temp = *a ;
    	*a = *b;
    	*b = temp  ;
    
    	//销毁调用方指针
    	//a = NULL ;
    	//b = NULL ;
    
    	printf("swap_point:[0x%x] , [0x%x] 
    " , &a , &b) ;
    }
    
    
    void swap(int * a , int * b){
    	int temp = *a ;
    	*a = *b;
    	*b = temp  ;
    
    	//销毁调用方指针无效
    	//a = NULL ;
    	//b = NULL ;
    
    	printf("swap:[0x%x] , [0x%x] 
    " , &a , &b) ;
    }
    
    void swap(int & a , int & b){
    	int temp = a ;
    	a = b ;
    	b = temp ;
    
    	printf("swap:[0x%x] , [0x%x] 
    " , &a , &b) ;
    }
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	/*int *ptr[3];
    
    	for(int i = 0 ; i < 3 ; i++){
    		ptr[i] = new int[5] ;
    		for(int l = 0 ; l < 5 ; l++){
    			ptr[i][l] = i * l ;
    			printf("%d * %d = %d 
     " , i , l , ptr[i][l] ) ;
    		}
    	}*/
    
    
    	/*int (*ptr)[3] ;
    
    	ptr = (int (*) [3])malloc(sizeof(int *) * 5) ;
    
    	for(int i = 0 ; i < 5 ; i++){
    		(*ptr)[0] = 1;
    		(*ptr)[1] = 2;
    		(*ptr)[2] = 3;
    		ptr++ ;
    	}
    
    
    	//初使化数组
    	char y[9][9] = {0};*/
    
    	int a = 3 ;
    	int b = 4 ;
    
    	//指针通过值传递(无法修改调用方指针变量值),调用swap ,指针变量  ptra , ptrb 按【值】传递 , 其中  swap 中 int * a , int * b 分别copy   ptra , ptrb 指针变量
    	int * ptra = &a ;
    	int * ptrb = &b ;
    	swap(ptra , ptrb) ;
    	printf("a = %d [0x%x] , b = %d[0x%x] , ptra = [0x%x] , ptrb = [0x%x] 
    " , a , &a , b , &b  , &ptra , &ptrb ) ;
    
    	//指针通过引用传递(能修改调用方指针变量值),调用swap_point ,指针变量  ptra , ptrb 按【引用】传递 , 其中  swap 中 int * a , int * b 即 ptra , ptrb 指针变量
    	swap_point(ptra , ptrb) ;
    	printf("a = %d [0x%x] , b = %d[0x%x] , ptra = [0x%x] , ptrb = [0x%x] 
    " , a , &a , b , &b  , &ptra , &ptrb ) ;
    
    	//按引用传递
    	 a = 3 ;
    	 b = 4 ;
    	swap(a , b) ;
    	printf("a = %d [0x%x] , b = %d[0x%x] 
    " , a , &a , b , &b) ;
    
    	system("pause");
    
    	return 0;
    }
    
  • 相关阅读:
    “图灵&博客园&互动网有奖书评征集活动——微软技术系列”评选结果
    像优秀的SQL程序员一样思考
    倚天·屠龙——唯我独尊
    CSS与HTML设计模式全集(350余种)
    游览器兼容冲突的常见css
    嵌入多媒体文本
    删除确认代码
    用!important解决IE和Mozilla的布局差别
    四大游览器兼容问题综合实例
    jQuery事件之鼠标事件
  • 原文地址:https://www.cnblogs.com/a_bu/p/7366791.html
Copyright © 2020-2023  润新知