这个c++代码是如何在没有定义函数的情况下运行的

How this c++ code runs without definition of function

本文关键字:定义 函数 情况下 运行 代码 c++ 这个      更新时间:2023-10-16

任何人都能解释这个程序中定义函数工作背后的逻辑吗。在这种情况下,即使在注释了函数的整个逻辑之后,也会给出正确的输出。

#include <iostream>
using namespace std;
void swap(int *a, int *b)
{ /*
int temp=0;
temp= *a;
*a= *b;
*b=temp;
*/
}
int main()
{
int x, y;
cout << "This program is the demo of function call by pointer nn";
cout << "Enter the value of x & y n";
cout << "x: ";
cin >> x;
cout << "y: ";
cin >> y;
cout << "Value befor swap " << endl;
cout << "x= " << x << " y= " << y << endl;
swap(x, y);
cout << "Value after swap " << endl;
cout << "x= " << x << " y= " << y << endl;
return 0;
}

这就是为什么不应该执行using namespace std;,它只会导致这样的混乱。

实际情况是,当您执行swap(x, y);时,会调用std::swap

顺便说一句,你的交换不起作用。它需要int指针,但你给它int。这不会编译,您需要执行swap(&x, &y);。它之所以有效,是因为它一直在使用std::swap

swap在您的定义和std::swap之间不明确。如果您想保留using namespace std,您需要将方法声明封装在类或命名空间中,并显式调用YourNamespaceOrClass::swap(a, b)

声明using namespace std;意味着您正在使用namespace std中的所有函数。现在,在您的代码中,您有自己版本的swap函数,即void swap(int *a, int *b)

由于namespace std具有接受整数的swap((预定义函数,因此该程序运行良好。如果没有这一点,您的程序将无法工作,因为您创建的函数需要一个指针。也就是说,您需要传递变量swap(&var1, &var2)的地址。

这被称为函数重载。它会根据参数找到合适的函数。

提示:避免使用using namespace std;,因为如果您不喜欢创建的函数,在更大的项目中会出现问题(冲突(。