在C++中将值传递给指针参数

Aks*_*hat 4 c++ pointers parameter-passing

在下面的代码中,为什么交换函数以两种方式工作,通过将值传递为swap(x,y)和swap(&x,&y).

int main(){

   int x, y;

   cout << "Enter the values of x and y: ";
   cin >> x >> y;

   swap(x, y);

   cout << "\nSwapped values are, x: " << x << " & y: " << y <<"\n";

   return 0;

}

void swap(int *a, int *b){

   int s;
   s = *a;
   *a = *b;
   *b = s;

}
Run Code Online (Sandbox Code Playgroud)

app*_*ple 7

std::swap你写的时候打电话swap(x, y);


在您的示例中,即使您编写,swap(&x, &y);您也只会遇到编译错误,除非您void swap(int*,int*);之前声明main.

并且std::swap对此无能为力int*,因为它无法将rvalue转换为int*&.(即使它能够做到这一点,就不会掉的价值xy)



leg*_*s2k 7

这是对另一个答案的解释,为什么std::swap被称为:

当你swap(x, y),编译器试图寻找一个swap要调用的重载.假设您已编写using std::swap;或者using namespace std;,编译器允许查看的命名空间将是全局的std.

原型void swap(int, int)是预期的,但编译器对选项开放 - 具有相同名称,相同计数参数但需要强制的不同参数类型的函数也可以 - 当寻找可行的重载时; 在枚举它们之后,它会选择最接近的匹配.

您在全局命名空间中实现的那个是类型

void swap(int*, int*);
Run Code Online (Sandbox Code Playgroud)

标准库头部<utility>给出的是函数模板

namespace std {
    template <typename T>
    void swap(T&, T&);
}
Run Code Online (Sandbox Code Playgroud)

这种超负荷已成为void swap(int&, int&)T = int.现在这是一个身份匹配(不需要类型强制),因此赢得了重载决议.

如果你没有写using std::swap;using namespace std;,那么编译器可用的唯一可能的重载将是你的,你已经得到一个错误,说参数类型不匹配.修复它将修复调用代码传递int*(这些变量的地址是类型指针int),而不是int:

swap(&x, &y);
Run Code Online (Sandbox Code Playgroud)