c++ - 通过辩论的区别
问题描述
大家好我写了两个代码
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();
}
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();
}
在这两种情况下,我都得到与交换前 a 的值相同的输出 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;
}
交换(a,b)没有问题并且工作正常,但是当我将值作为交换(&a,&b)传递时,代码给出错误错误C2665:'swap':3个重载都不能转换所有参数类型为什么?
解决方案
问题是这条邪恶的线:
using namespace std;
在您的第二个示例中,您实际上是在调用::std::swap
. 由于您的版本swap
需要指针,因此您必须使用&
运算符。
推荐阅读
- c# - 从商店安装后启动应用程序未启动
- vue.js - 将 v-for 生成的单选按钮的值设置为 true
- sqlite - react-native-sqlite-storage 的多行查询未定义
- java - 拖动时:如何使视图不可见但拖动阴影不透明?
- python - 错误:安装 osmnx 的“python setup.py egg_info”失败,错误代码为 1”
- c# - 如何拥有一个包含两个模型的视图模型
- android - 无法在 Android Pie 上使用颤振声音插件播放音乐
- c - 如果 .sh 文件和 linux c 文件的路径不同,那么如何使用系统命令呢?看过一个回答。在stackoverflow上但不清楚
- r - R中的bin和转置
- python - 在背景上创建 python 图