下列為一個 C++語言的副程式,用來交換輸入的變數值: void swap(int &x,int *y){ int a; a = x; x = *y; *y = a; } 若於主程式內宣告兩個變數 int m=3, n=2; 則主程式中應如何呼叫 swap副程式才能正確在主程式執行完後m=2, n=3?
Aswap (m,n)
Bswap(&m,n)
Cswap(m,&n)正確答案
Dswap(&m,&n)
答案與詳解
正解。m 對應 reference 參數直接寫 m;n 對應 pointer 參數寫 &n 傳位址,兩者皆能在函式內修改原值,達成交換。
