非引用傳遞:
答:當用實參副本初始化形參時,函數並沒有訪問調用所傳遞的實參本身,因此不會修改實參的值。
指針形參:
答:與其他非引
用類型的形參一樣,該類形參的任何改變也僅作用於局部副本。
例如:
void reset(int *ip)
313
{
*ip = 0; // changes the value of the object to which i p points
ip = 0; // changes only the local value of ip; the argument
is unchanged
}
調用 reset 後,實參依然保持原來的值,但它所指向的對象的值將變爲 0:
int i = 42;
int *p = &i;
cout << "i: " << *p << '\n'; // prints i: 42
reset(p); // changes *p but not p
cout << "i: " << *p << endl; // ok: prints i: 0
引用參數:
答:引用形參直接關聯到其所綁定的實參。
void swap(int &v1, int &v2)
{
int tmp = v2;
v2 = v1;
v1 = tmp;
}
複製實參副本會帶來什麼問題?
答:當實參對象較大時,效率會很低;所以會選擇用加const的引用參數。
含有可變形參的函數:
答:省略符形參有下列兩種形式:
void foo(parm_list, ...);
void foo(...);
爲什麼有些函數的返回類型是void,卻要用return?
答:因爲返回類型是 void 的函數使用 return 語句是爲了引起函數的強制結束。
如:
// ok: swap acts on references to its arguments
void swap(int &v1, int &v2)
{
// if values already the same, no need to swap, just return
if (v1 == v2)
return;
// ok, have work to do
int tmp = v2;
v2 = v1;
v1 = tmp;
// no explicit return necessary
}