我正在学习C++,只是发现了一些我想理解的奇怪东西(请参阅代码第 5 行的注释):
#include <iostream>
using namespace std;
// WITH this forward decleration the output is A=1 and B=2
// WITHOUT this forward decleration the output is A=2 and B=1
// WHY??
void swap(int a, int b);
int main() {
int a = 1;
int b = 2;
swap(a, b);
cout << "A: " << a << endl;
cout << "B: " << b << endl;
system("PAUSE");
return 0;
}
void swap(int a, int b) {
int tmp = a;
a = b;
b = tmp;
}
有人可以解释一下这种行为吗?我认为默认情况下 c++ 按值传递,除非您在函数参数前面使用 amperstand (&),如下所示:
function swap(int &a, int &b) {
swap
的实现在函数中本地交换值,因为它的参数是按值传递的。它不会更改调用函数中的任何内容。
当您没有该函数声明时,将使用std::swap
,这执行正确的操作。
首先,你的交换函数不会交换原始参数。它交换原始参数的副本,这些参数将在退出函数后销毁。如果您希望函数确实会交换原始参数,则必须将参数声明为引用
void swap(int &a, int &b) {
int tmp = a;
a = b;
b = tmp;
}
当程序中没有函数的前向声明时,编译器似乎选择了交换原始参数的标准函数std::swap
。由于 using 指令,编译器会考虑标准函数std::swap
using namepsace std;
如果删除它并删除函数的前向声明,则编译器将发出错误。
当函数的前向声明存在时,编译器会选择您的函数,因为它与非模板函数最匹配。