我正在学习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) {发布于 2015-03-16 22:20:18
首先,交换函数不交换原始参数。它交换退出函数后将销毁的原始参数的副本。如果希望函数确实交换原始参数,则必须将参数声明为引用。
void swap(int &a, int &b) {
int tmp = a;
a = b;
b = tmp;
}当程序中没有函数的前向声明时,编译器似乎选择了交换原始参数的标准函数std::swap。由于使用指令,标准函数std::swap由编译器考虑。
using namepsace std;如果删除它并删除函数的前向声明,则编译器将发出错误。
当函数的前向声明出现时,编译器将选择您的函数,因为它是与非模板函数最匹配的函数。
https://stackoverflow.com/questions/29087765
复制相似问题