ris*_*dey 1 c++ swap overloading pass-by-reference name-lookup
大家好我写了两个代码
1.
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
int main()
{
int a = 10, b = 20;
cout << "value of a before swap " << a << endl;
cout << "value of b before swap " << b << endl;
swap(&a, &b);
cout << "value of a after swap " << a << endl;
cout << "value of b after swap " << b << endl;
cin.get();
}
Run Code Online (Sandbox Code Playgroud)
2.
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
int main()
{
int a = 10, b = 20;
cout << "value of a before swap " << a << endl;
cout << "value of b before swap " << b << endl;
swap(a, b);
cout << "value of a after swap " << a << endl;
cout << "value of b after swap " << b << endl;
cin.get();
}
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,我得到的输出与交换前 10 交换前 b 的值交换前 20 交换后 a 的值 20 交换后 10 后 b 的值相同
我的第一个问题是 swap(&a,&b) 和 swap(a,b) 对交换函数没有影响吗??
但是当我给下面的交换函数给出相同的参数时
void swap(int &x, int &y)
{
int t;
t = x;
x = y;
y = t;
}
Run Code Online (Sandbox Code Playgroud)
swap(a,b) 没有问题并且工作正常,但是当我将值作为 swap(&a,&b) 传递时,代码给出错误错误 C2665: 'swap': 3 个重载中没有一个可以转换所有参数类型 为什么?
问题是这条邪恶的线:
using namespace std;
Run Code Online (Sandbox Code Playgroud)
在您的第二个示例中,您实际上是在调用::std::swap. 由于您的版本swap采用指针,因此您必须使用&运算符。
请参阅为什么“使用命名空间 std;” 被认为是不好的做法?