我觉得和编译器关系不大,按引用传递和按值传递时的函数声明位置有点搞不懂,例如下面两个程序。
程序一:按值传递
#include <iostream>
using namespace std;
void swap(int x, int y);
int main()
{
int x = 5, y = 10;
cout << "Main. Before swap, x: " << x << " y: " << y << endl;
swap(x,y);
cout << "Main. After swap, x: " << x << " y: " << y << endl;
return 0;
}
void swap (int x, int y)
{
int temp;
cout << "Swap. Before swap, x: " << x << " y: " << y << endl;
temp = x;
x = y;
y = temp;
cout << "Swap. After swap, x: " << x << " y: " << y << endl;
}
这个程序中将swap函数的声明放在main函数内部和外部时的编译结果是相同的。
程序二:按引用传递。
#include <iostream>
using namespace std;
void swap(int &x, int &y);
int main()
{
int x = 5, y = 10;
cout << "Main. Before swap, x: " << x << " y: "
<< y << endl;
swap(x,y);
cout << "Main. After swap, x: " << x << " y: "
<< y << endl;
return 0;
}
void swap (int &rx, int &ry)
{
int temp;
cout << "Swap. Before swap, rx: " << rx << " ry: "
<< ry << endl;
temp = rx;
rx = ry;
ry = temp;
cout << "Swap. After swap, rx: " << rx << " ry: "
<< ry << endl;
}
在此程序中,swap函数的声明在main函数内部和外部时编译结果又不一样了。
[[it] 本帖最后由 rustleer 于 2008-11-6 17:49 编辑 [/it]]