ITPub博客

首页 > 应用开发 > > 函数参数为指针的值传递与引用传递

函数参数为指针的值传递与引用传递

作者:dav2100 时间:2019-08-20 11:11:46 0 删除 编辑

1.问题的由来:今天在实现二叉树的创建和遍历的时候,发现在(二叉树的建立的参数的)代码中少了一个引用符号,然后编译器会报错:”使用了未初始化的局部变量“,在我使用了引用之后,便没有了这样的错误。

2.给出代码

1 #include<iostream>
 2 using namespace std;
 3 
 4 typedef char element_type; //declare that element's type is char
 5 typedef struct Bnode {
 6     element_type data;
 7     struct Bnode *Lson, *Rson;
 8 } Bnode, *Bptr;
 9 //create a prologue Btree
10 int createBtree(Bptr &T) {
11     char data;
12     cin >> data;
13     if (data == '#') {
14         T = NULL;
15     }
16     else {
17         T = new Bnode();//assign the space for the root
18         T->data = data;
19         createBtree(T->Lson);
20         createBtree(T->Rson);
21     }
22     return 0;
23 }
24 void visit(Bptr T) {
25     if (T->data != '#') {
26         cout << T->data;
27     }
28 }
29 void inorder(Bptr p) { //p points to the root of the Btree
30     if (p == NULL) return;
31     inorder(p->Lson);
32     visit(p);
33     inorder(p->Rson);
34 }
35 void postorder(Bptr p) { //p points to the root of the Btree
36     if (p == NULL) return;
37     postorder(p->Lson);
38     postorder(p->Rson);
39     visit(p);
40 }
41 int main()
42 {
43     Bptr T;
44     cout << "输入字符串,建立二叉树: ";
45     createBtree(T);
46     cout << "二叉树的中序遍历: ";
47     inorder(T);
48     cout << endl;
49     cout << "二叉树的后序遍历: ";
50     postorder(T);
51     cout << endl;
52     system("pause");
53 }

3.问题出在第10行。

4.做过了哪些尝试:

(1)把43行改为:Bptr T=NULL。结果编译成功了,但是没有实现功能

5.疑问:为什么要用引用? 为什么遍历函数不用引用就没事,而构建二叉树必须要引用参数呢?

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4479/viewspace-3171479/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2019-10-17

  • 博文量
    176
  • 访问量
    17570