2

所以我的疑问是,我正在尝试按值调用,在运行给定代码时,当我在 int main() 之后编写函数定义时发生交换但是如果我在 int main() 上方剪切并粘贴函数定义,则交换确实不发生。这是为什么?


#include<iostream>
#include<string>
#include<vector>
#include<bitset>
#include<fstream>
using namespace std;
#define ADDU 1
#define SUBU 3
#define AND 4
#define OR  5
#define NOR 7
#define MemSize 65536
void swap(int a, int b)
{
    int temp = a;
    a = b;
    b = temp;
}

int main(){
    // int a = 20;
    // int *p = &a;
    // cout<<"P: "<<p<<endl<<"*P gives: "<<*p<<endl<<"&p gives: "<<&p<<endl<<"&a : "<<&a;;

    int x,y;
    x = 10;
    y = 20;
    cout<<"Before Swapping: "<<"x: "<<x<<endl<<"y: "<<y<<endl;
    swap(x,y);
    cout<<"After Swapping: "<<"x: "<<x<<endl<<"y: "<<y<<endl;
}
4

1 回答 1

9

您的交换函数并没有真正交换任何东西,因为它通过值而不是通过引用来获取它的参数。您所做的只是操作该函数的本地变量。

当你直到after main才引入它时,它不在你调用它的范围内,所以std::swap被使用。std::swap工作正常。

尽管您没有具体说明std::swap,但您写using namespace std;的内容删除了该要求(有充分的理由不这样做!!)。而且,尽管您没有,但您#include <algorithm>不能保证哪些标准标头最终可能会由于实现的构造方式而包含其他标头。

于 2019-10-09T23:25:04.187 回答