簡體   English   中英

將指向結構成員的指針傳遞給函數

[英]Passing pointer to a member of a struct to a 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;
}

但是,當我使用以下內容時:

swap(r1->len,r1->wid);

代替:

swap(&r1->len,&r1->wid);

我仍然得到正確的結果,我不確定它是如何工作的。 根據我的理解,我應該使用(&r1->)將成員變量的地址傳遞給函數。 有人可以解釋一下嗎?

您正在using namespace std;

在標准c ++庫中存在此版本的swap函數 ,該函數接受兩個引用並駐留在std命名空間中。

當您使用& ,會調用您的函數。 如果你不是,那就是來自標准庫的那個。 實際上,使用using指令,您不需要在函數名前面添加std:: 因此,在您的情況下,您的swap函數作為標准庫中的swap函數的重載存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM