1. 程式人生 > >C++ 函數參數中“ *&代表什麽? ”

C++ 函數參數中“ *&代表什麽? ”

pri index dao namespace har break postorder reat sizeof

typedef struct BitNode
{
char value;
BitNode *lchild,*rchild;
}BitNode,*BiTree;

void CreatTree(BitNode* &root,char *pre,int l1,int r1,char *in,int l2,int r2) ;

/* *&代表什麽? //https://zhidao.baidu.com/question/2266744263935050308.html

這是C++的語法寫法,&在形參中表示“引用”實參,
LNode * &lst ; 中LNode * 是個整體,表示變量類型是LNode類指針, &lst中的&表明引用實參,即代表實參的一個別名。
標準C是不支持這種寫法的。

追問

&不是取地址符嗎? 引用參數是什麽意思

追答

&在變量定義區,表示引用,要註意它的用法,
&在變量操作區,表示取地址符,如:

int x=10, *p=&x ; //這裏&作用在x上, 是取地址符
int &x ; //引用是C++引入的一個新特性,你要學的不是C++,則上述代碼你是搞不懂的。 這裏的&就表示引用。 一般這種形式會在形參中出現。

LNode * &lst ; 中LNode * 是個整體,表示變量類型是LNode類指針, &lst中的&表明引用實參,即代表實參的一個別名。 操作引用變量就相當於操作實參變量



*/

利用前序和中序求二叉樹(源代碼):

    1. #include <iostream>
    2. #include <cstdio>
    3. #include <cstdlib>
    4. #include <cstring>
    5. using namespace std;;
    6. const int N=31;
    7. typedef struct BitNode
    8. {
    9. char value;
    10. BitNode *lchild,*rchild;
    11. }BitNode,*BiTree;
    12. /* *&代表什麽?
    13. 這是C++的語法寫法,&在形參中表示“引用”實參,
    14. LNode * &lst ; 中LNode * 是個整體,表示變量類型是LNode類指針, &lst中的&表明引用實參,即代表實參的一個別名。
    15. 標準C是不支持這種寫法的。
    16. 追問
    17. &不是取地址符嗎? 引用參數是什麽意思
    18. 追答
    19. &在變量定義區,表示引用,要註意它的用法,
    20. &在變量操作區,表示取地址符,如:
    21. int x=10, *p=&x ; //這裏&作用在x上, 是取地址符
    22. int &x ; //引用是C++引入的一個新特性,你要學的不是C++,則上述代碼你是搞不懂的。 這裏的&就表示引用。 一般這種形式會在形參中出現。
    23. LNode * &lst ; 中LNode * 是個整體,表示變量類型是LNode類指針, &lst中的&表明引用實參,即代表實參的一個別名。 操作引用變量就相當於操作實參變量
    24. */
    25. void CreatTree(BitNode* &root,char *pre,int l1,int r1,char *in,int l2,int r2)
    26. {
    27. if(l1<=r1&&l2<=r2)
    28. {
    29. int key=pre[l1];
    30. int midIndex=-1;
    31. for(int i=l2;i<=r2;i++)
    32. {
    33. if(in[i]==key)
    34. {
    35. midIndex=i;
    36. break;
    37. }
    38. }
    39. root=(BitNode *)malloc(sizeof(BitNode));
    40. root->value=key;
    41. root->lchild=NULL;
    42. root->rchild=NULL;
    43. int llen=midIndex-l2;
    44. CreatTree(root->lchild, pre, l1+1, l1+llen, in, l2, midIndex-1);
    45. CreatTree(root->rchild, pre, l1+llen+1, r1, in, midIndex+1, r2);
    46. }
    47. }
    48. void postOrderTraverse(BitNode *&root)
    49. {
    50. if(root->lchild)
    51. postOrderTraverse(root->lchild);
    52. if(root->rchild)
    53. postOrderTraverse(root->rchild);
    54. printf("%c",root->value);
    55. }
    56. int main()
    57. {
    58. char pre[N],in[N];
    59. while(scanf("%s",pre)!=EOF)
    60. {
    61. scanf("%s",in);
    62. int len1=strlen(pre);
    63. int len2=strlen(in);
    64. BitNode *root=NULL;
    65. CreatTree(root,pre,0,len1-1,in,0,len2-1);
    66. postOrderTraverse(root);
    67. printf("\n");
    68. }
    69. return 0;
    70. }

C++ 函數參數中“ *&代表什麽? ”