C/C++函數(shù)參數(shù)傳遞機(jī)制詳解及實(shí)例
概要:
C/C++的基本參數(shù)傳遞機(jī)制有兩種:值傳遞和引用傳遞,我們分別來(lái)看一下這兩種的區(qū)別。
(1)值傳遞過(guò)程中,需在堆棧中開辟內(nèi)存空間以存放由主調(diào)函數(shù)放進(jìn)來(lái)的實(shí)參的值,從而成為了實(shí)參的一個(gè)副本。值傳遞的特點(diǎn)是被調(diào)函數(shù)對(duì)形參的任何操作都是作為局部變量進(jìn)行,不會(huì)影響主調(diào)函數(shù)的實(shí)參變量的值。
(2)引用傳遞過(guò)程中,被調(diào)函數(shù)的形參雖然也作為局部變量在堆棧中開辟了內(nèi)存空間,但是這時(shí)存放的是由主調(diào)函數(shù)放進(jìn)來(lái)的實(shí)參變量的地址。被調(diào)函數(shù)對(duì)形參的任何操作都被處理成間接尋址,即通過(guò)堆棧中存放的地址訪問(wèn)主調(diào)函數(shù)中的實(shí)參變量。正因?yàn)槿绱耍徽{(diào)函數(shù)對(duì)形參做的任何操作都影響了主調(diào)函數(shù)中的實(shí)參變量。
下面我們來(lái)看一個(gè)示例。
/**測(cè)試函數(shù)參數(shù)傳遞機(jī)制*/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;}看一下我們的測(cè)試代碼和測(cè)試結(jié)果。
//測(cè)試代碼邏輯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;}//測(cè)試結(jié)果面積:100面積:200rect.height:30面積:300rect.height:30可以發(fā)現(xiàn)傳址調(diào)用和引用傳遞兩種方式,當(dāng)改變形參的值時(shí),同時(shí)也會(huì)將實(shí)參的值改變,而傳值調(diào)用改變形參則對(duì)實(shí)參沒有任何影響。
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答