加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 关于指针的引用

发布时间:2020-12-16 10:11:40 所属栏目:百科 来源:网络整理
导读:我一直在做树,因为种树会拯救地球(或只是程序). class Tree { Node* root; // ... void insert(int value){ private_insert(value,root); } void insert_private(int value,node* n){ if(n == nullptr){ n = new node(value); } else { your standard recurs
我一直在做树,因为种树会拯救地球(或只是程序).

class Tree {
  Node* root;
  // ...
  void insert(int value){
    private_insert(value,root);
  }
  void insert_private(int value,node* n){
    if(n == nullptr){
      n = new node(value);
    } else {
      your standard recursive insertion function here
    }
  }
  // ...
};

长话短说我先尝试过使用shared_ptrs,但insert()函数永远不会在我的树中添加任何元素.我以为我可能会对共享做错了所以我尝试了原始指针,并且我得到了相同的非插入式resoults.

结果我需要传递一个引用我的root / nodes.

void insert_private(int value,node*& n) {...};

我明白,如果我不传递某些东西作为参考,那么就会制作一份副本.但是如果一个指针持有一个地址,它的副本是否保持相同的地址?如果我为一个非引用指针创建一个new(),为什么它不会粘在我的根/节点上?

为什么我的问题在这里,我可以接受它,它的工作原理,我的树工作,但我不知道为什么它像这样.

编辑:阅读评论后,我创建了这个小专家级程序:

void fn(int* i){
  cout << "Address of local in fn before change: " << i << endl;
  i = new int(2);
// so basically here we made a new int,and i will get the address of 
// this integer and will point to there,what we passed on before 
// becomes irrelevant
  cout << "Address of local in fn after change: " << i << endl;
}
void fn2(int **i){
  cout << "Address of local in fn2 before change: " << i << endl;
  *i = new int(2);
  cout << "Address of local in fn2 after change: " << i << endl;
}
int main(){
  int* p = nullptr;
  cout << "Address of p: " << p << endl;
  fn(p);
  cout << "p& is: " << &p << endl;
  fn2(&p);

  cin.get();
  return 0;
};

谢谢大家的答案,它帮助了很多. random.org将确定谁将获得批准答案的人.

解决方法

是的它是一个副本,它保存相同的地址,但是您只分配给该副本,该副本在函数返回时被丢弃.原件没有改变.那是你的问题.

顺便说一句,恕我直言,如果你改变一个参数的值,你应该使用一个指针,因此指向你的情况下的指针.这使得读者更清楚地知道你正在改变价值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读