非引用传递:
答:当用实参副本初始化形参时,函数并没有访问调用所传递的实参本身,因此不会修改实参的值。
指针形参:
答:与其他非引
用类型的形参一样,该类形参的任何改变也仅作用于局部副本。
例如:
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
}