将指向结构成员的指针传递给函数

use*_*117 2 c++ pointers structure function

我使用以下程序来交换矩形结构的长度和宽度

typedef struct rectangle
{
  int len;
  int wid;
} rect;

void swap(int* a, int * b)
{
  int temp;
  temp= *a;     
  *a=*b;
  *b=temp;
}

int main()
{
  rect rect1;
  rect *r1;
  r1= &rect1;
  r1->len=10;
  r1->wid=5;

  cout<< "area of rect " << r1->len * r1->wid<<endl;
  swap(&r1->len,&r1->wid);

  cout<< "length=" << rect1.len<<endl;
  cout<<"width=" <<rect1.wid;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我使用以下内容时:

swap(r1->len,r1->wid);
Run Code Online (Sandbox Code Playgroud)

代替:

swap(&r1->len,&r1->wid);
Run Code Online (Sandbox Code Playgroud)

我仍然得到正确的结果,我不确定它是如何工作的.根据我的理解,我应该使用(&r1->)将成员变量的地址传递给函数.有人可以解释一下吗?

Nbr*_*r44 8

你是using namespace std;.

在标准c ++库中存在此版本的交换函数,它接受两个引用并驻留在std命名空间中.

会发生什么事情,当您使用时&,您的功能将被调用.如果你不是,那就是来自标准库的那个.实际上,使用该using指令,您无需std::在函数名称前添加.因此,在您的情况下,您的swap函数作为标准库中的函数的重载存在.

  • 这就是为什么把`using namespace std`放在一起是不好的做法. (3认同)