C++ 實值型別和參考型別傳遞樣本

來源:互聯網
上載者:User

標籤:i++   test   無法   無效   size   printf   參考型別   修改   new   

// 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] \r\n" , &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] \r\n" , &a , &b) ;}void swap(int & a , int & b){int temp = a ;a = b ;b = temp ;printf("swap:[0x%x] , [0x%x] \r\n" , &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 \r\n " , 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] \r\n" , 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] \r\n" , a , &a , b , &b  , &ptra , &ptrb ) ;//按引用傳遞 a = 3 ; b = 4 ;swap(a , b) ;printf("a = %d [0x%x] , b = %d[0x%x] \r\n" , a , &a , b , &b) ;system("pause");return 0;}

 

C++ 實值型別和參考型別傳遞樣本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.