【发布时间】:2015-03-16 22:01:50
【问题描述】:
我正在学习 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++ 按值传递,除非您在函数参数前面使用符号 (&),如下所示:
function swap(int &a, int &b) {
【问题讨论】:
-
如果您同时删除该指令和 using 指令,它将无法编译,如您所料。
-
@chris 不是真的,
std::swap实现了正确的交换(不像他的)。 -
@0x499602D2,是的,我知道。 Here's what I mean.
标签: c++ visual-studio gcc syntax forward-declaration