C++ 函數參數中“ *&代表什麽? ”
阿新 • • 發佈:2018-08-31
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中的&表明引用實參,即代表實參的一個別名。 操作引用變量就相當於操作實參變量
*/
利用前序和中序求二叉樹(源代碼):
- using namespace std;;
- const int N=31;
- typedef struct BitNode
- {
- char value;
- BitNode *lchild,*rchild;
- }BitNode,*BiTree;
- /* *&代表什麽?
- 這是C++的語法寫法,&在形參中表示“引用”實參,
- LNode * &lst ; 中LNode * 是個整體,表示變量類型是LNode類指針, &lst中的&表明引用實參,即代表實參的一個別名。
- 標準C是不支持這種寫法的。
- 追問
- &不是取地址符嗎? 引用參數是什麽意思
- 追答
- &在變量定義區,表示引用,要註意它的用法,
- &在變量操作區,表示取地址符,如:
- int x=10, *p=&x ; //這裏&作用在x上, 是取地址符
- int &x ; //引用是C++引入的一個新特性,你要學的不是C++,則上述代碼你是搞不懂的。 這裏的&就表示引用。 一般這種形式會在形參中出現。
- LNode * &lst ; 中LNode * 是個整體,表示變量類型是LNode類指針, &lst中的&表明引用實參,即代表實參的一個別名。 操作引用變量就相當於操作實參變量
- */
- void CreatTree(BitNode* &root,char *pre,int l1,int r1,char *in,int l2,int r2)
- {
- if(l1<=r1&&l2<=r2)
- {
- int key=pre[l1];
- int midIndex=-1;
- for(int i=l2;i<=r2;i++)
- {
- if(in[i]==key)
- {
- midIndex=i;
- break;
- }
- }
- root=(BitNode *)malloc(sizeof(BitNode));
- root->value=key;
- root->lchild=NULL;
- root->rchild=NULL;
- int llen=midIndex-l2;
- CreatTree(root->lchild, pre, l1+1, l1+llen, in, l2, midIndex-1);
- CreatTree(root->rchild, pre, l1+llen+1, r1, in, midIndex+1, r2);
- }
- }
- void postOrderTraverse(BitNode *&root)
- {
- if(root->lchild)
- postOrderTraverse(root->lchild);
- if(root->rchild)
- postOrderTraverse(root->rchild);
- printf("%c",root->value);
- }
- int main()
- {
- char pre[N],in[N];
- while(scanf("%s",pre)!=EOF)
- {
- scanf("%s",in);
- int len1=strlen(pre);
- int len2=strlen(in);
- BitNode *root=NULL;
- CreatTree(root,pre,0,len1-1,in,0,len2-1);
- postOrderTraverse(root);
- printf("\n");
- }
- return 0;
- }
C++ 函數參數中“ *&代表什麽? ”