这个c++代码是如何在没有定义函数的情况下运行的
How this c++ code runs without definition of function
任何人都能解释这个程序中定义函数工作背后的逻辑吗。在这种情况下,即使在注释了函数的整个逻辑之后,也会给出正确的输出。
#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;
,因为如果您不喜欢创建的函数,在更大的项目中会出现问题(冲突(。
相关文章:
- 在命名空间中定义函数还是限定函数
- 为什么在定义函数之前先声明它
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 这个c++代码是如何在没有定义函数的情况下运行的
- 具有外部"c"和程序集的未定义函数
- 已定义函数时出现 G++ "未定义的引用"错误
- 将自定义函数传递到基抽象类中以延迟执行
- C++使用 rand 定义函数语法
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题
- 将具有固定签名的自定义函数名称注入 CRTP
- 使用定义函数模板别名
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 在内联程序集中定义函数和从 C++ 调用时出现问题
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 声明和定义函数静态会产生"undefined reference to function_name()"
- 朋友定义函数的名称空间是什么
- 介子 对用户定义函数的未定义引用
- 如何使用 "using" 关键字定义函数原型/签名
- 在 C 结构中定义C++函数