C/C++函數(shù)參數(shù)傳遞機制詳解及實例
C/C++函數(shù)參數(shù)傳遞機制詳解及實例
概要:
C/C++的基本參數(shù)傳遞機制有兩種:值傳遞和引用傳遞,我們分別來看一下這兩種的區(qū)別。
(1)值傳遞過程中,需在堆棧中開辟內(nèi)存空間以存放由主調(diào)函數(shù)放進(jìn)來的實參的值,從而成為了實參的一個副本。值傳遞的特點是被調(diào)函數(shù)對形參的任何操作都是作為局部變量進(jìn)行,不會影響主調(diào)函數(shù)的實參變量的值。
(2)引用傳遞過程中,被調(diào)函數(shù)的形參雖然也作為局部變量在堆棧中開辟了內(nèi)存空間,但是這時存放的是由主調(diào)函數(shù)放進(jìn)來的實參變量的地址。被調(diào)函數(shù)對形參的任何操作都被處理成間接尋址,即通過堆棧中存放的地址訪問主調(diào)函數(shù)中的實參變量。正因為如此,被調(diào)函數(shù)對形參做的任何操作都影響了主調(diào)函數(shù)中的實參變量。
下面我們來看一個示例。
/* *測試函數(shù)參數(shù)傳遞機制 */ class CRect { public: int height; int widht; CRect() { height = 0; widht = 0; } CRect(int height, int widht) { this->height = height; this->widht = widht; } }; //(1)傳址調(diào)用(傳指針) int RectAreaPoint(CRect *rect) { int result = rect->height * rect->widht; rect->height = 20; return result; } //(2)引用傳遞 int RectAreaRefer(CRect &rect) { int result = rect.height * rect.widht; rect.height = 30; return result; } //(3)傳值調(diào)用 int RectArea(CRect rect) { int result = rect.height * rect.widht; rect.height = 40; return result; }
看一下我們的測試代碼和測試結(jié)果。
//測試代碼邏輯 void testPoint() { CRect rect(10, 10); cout << "面積:" << RectAreaPoint(&rect) << endl; cout << "面積:" << RectAreaRefer(rect) << endl; cout << "rect.height:" << rect.height << endl; cout << "面積:" << RectArea(rect) << endl; cout << "rect.height:" << rect.height << endl; } //測試結(jié)果 面積:100 面積:200 rect.height:30 面積:300 rect.height:30
可以發(fā)現(xiàn)傳址調(diào)用和引用傳遞兩種方式,當(dāng)改變形參的值時,同時也會將實參的值改變,而傳值調(diào)用改變形參則對實參沒有任何影響。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
C語言自定義數(shù)據(jù)類型的結(jié)構(gòu)體、枚舉和聯(lián)合詳解
這篇文章主要給大家介紹了關(guān)于C語言自定義數(shù)據(jù)類型的結(jié)構(gòu)體、枚舉和聯(lián)合的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05