我使用下面的程序来交换矩形结构的长度和宽度
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;
}
但是,当我使用以下内容时:
swap(r1->len,r1->wid);
代替:
swap(&r1->len,&r1->wid);
我仍然得到正确的结果,但我不确定它是如何工作的。根据我的理解,我应该使用 (&r1->)
将成员变量的地址传递给函数。有人可以解释一下吗?
最佳答案
您正在使用命名空间标准;
。
标准c++库中存在this version of the swap function ,它有两个 references 并驻留在 std
命名空间中。
发生的事情是,当您使用&
时,您的函数将被调用。如果不是,它就是来自标准库的那个。事实上,使用 using
指令,您不需要在函数名前添加 std::
。因此,在您的情况下,您的 swap
函数作为标准库中函数的重载存在。
关于c++ - 将指向结构成员的指针传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18052526/