将交换函数放在文件末尾即可使其工作

问题描述 投票:0回答:1

我有一个交换两个数字的程序:

#include <iostream>
using namespace std;

void swap(int a, int b) {
    int temp;
    temp = a;
    a = b;
    b = temp;
}

int main() {
    int a, b;

    cout << "Enter the first number: ";
    cin >> a;
    cout << "Enter the second number: ";
    cin >> b;

    cout << "Before swapping, the first number was " << a << ", and the second was " << b << "." << endl;

    swap(a, b);

    cout << "After swapping, the first number is " << a << ", and the second is " << b << "." << endl;

    return 0;
}

当我运行它时,我得到以下输出:

Enter the first number: 1
Enter the second number: 3
Before swapping, the first number was 1, and the second was 3.
After swapping, the first number is 1, and the second is 3.

这是预期的,因为

swap
函数修改了函数内的变量
a
b
,并且这应该不会影响它们在
main
函数中的值。

但是,如果我将

swap
函数放在
main
函数之后,没有函数原型,则实际上会发生交换:

#include <iostream>
using namespace std;

int main() {
    int a, b;

    cout << "Enter the first number: ";
    cin >> a;
    cout << "Enter the second number: ";
    cin >> b;

    cout << "Before swapping, the first number was " << a << ", and the second was " << b << "." << endl;

    swap(a, b);

    cout << "After swapping, the first number is " << a << ", and the second is " << b << "." << endl;

    return 0;
}

void swap(int a, int b) {
    int temp;
    temp = a;
    a = b;
    b = temp;
}

上面产生以下输出:

Enter the first number: 1
Enter the second number: 3
Before swapping, the first number was 1, and the second was 3.
After swapping, the first number is 3, and the second is 1.

为什么会出现这种情况?有谁可以解释一下吗?

c++ function swap
1个回答
0
投票

如果我将交换函数放在主函数之后,没有函数原型,则交换实际上会发生:

是的,那是因为正在使用的不是 your

swap
函数,而是
std::swap

您可以通过删除

using namespace std;
或将函数命名为
MySwap
并在
main
之前为其提供原型来进行测试。

© www.soinside.com 2019 - 2024. All rights reserved.